Coverage Report

Created: 2023-02-12 01:41

/src/DLXEmu/external/imgui/imgui.cpp
Line
Count
Source (jump to first uncovered line)
1
// dear imgui, v1.89.3 WIP
2
// (main code and documentation)
3
4
// Help:
5
// - Read FAQ at http://dearimgui.org/faq
6
// - Newcomers, read 'Programmer guide' below for notes on how to setup Dear ImGui in your codebase.
7
// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.
8
// Read imgui.cpp for details, links and comments.
9
10
// Resources:
11
// - FAQ                   http://dearimgui.org/faq
12
// - Homepage & latest     https://github.com/ocornut/imgui
13
// - Releases & changelog  https://github.com/ocornut/imgui/releases
14
// - Gallery               https://github.com/ocornut/imgui/issues/5886 (please post your screenshots/video there!)
15
// - Wiki                  https://github.com/ocornut/imgui/wiki (lots of good stuff there)
16
// - Glossary              https://github.com/ocornut/imgui/wiki/Glossary
17
// - Issues & support      https://github.com/ocornut/imgui/issues
18
19
// Getting Started?
20
// - For first-time users having issues compiling/linking/running or issues loading fonts:
21
//   please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above.
22
23
// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
24
// See LICENSE.txt for copyright and licensing details (standard MIT License).
25
// This library is free but needs your support to sustain development and maintenance.
26
// Businesses: you can support continued development via invoiced technical support, maintenance and sponsoring contracts. Please reach out to "contact AT dearimgui.com".
27
// Individuals: you can support continued development via donations. See docs/README or web page.
28
29
// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
30
// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
31
// modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
32
// come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
33
// to a better solution or official support for them.
34
35
/*
36
37
Index of this file:
38
39
DOCUMENTATION
40
41
- MISSION STATEMENT
42
- END-USER GUIDE
43
- PROGRAMMER GUIDE
44
  - READ FIRST
45
  - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
46
  - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
47
  - HOW A SIMPLE APPLICATION MAY LOOK LIKE
48
  - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
49
  - USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS
50
- API BREAKING CHANGES (read me when you update!)
51
- FREQUENTLY ASKED QUESTIONS (FAQ)
52
  - Read all answers online: https://www.dearimgui.org/faq, or in docs/FAQ.md (with a Markdown viewer)
53
54
CODE
55
(search for "[SECTION]" in the code to find them)
56
57
// [SECTION] INCLUDES
58
// [SECTION] FORWARD DECLARATIONS
59
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
60
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
61
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
62
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
63
// [SECTION] MISC HELPERS/UTILITIES (File functions)
64
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
65
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
66
// [SECTION] ImGuiStorage
67
// [SECTION] ImGuiTextFilter
68
// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
69
// [SECTION] ImGuiListClipper
70
// [SECTION] STYLING
71
// [SECTION] RENDER HELPERS
72
// [SECTION] INITIALIZATION, SHUTDOWN
73
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
74
// [SECTION] INPUTS
75
// [SECTION] ERROR CHECKING
76
// [SECTION] LAYOUT
77
// [SECTION] SCROLLING
78
// [SECTION] TOOLTIPS
79
// [SECTION] POPUPS
80
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
81
// [SECTION] DRAG AND DROP
82
// [SECTION] LOGGING/CAPTURING
83
// [SECTION] SETTINGS
84
// [SECTION] LOCALIZATION
85
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
86
// [SECTION] DOCKING
87
// [SECTION] PLATFORM DEPENDENT HELPERS
88
// [SECTION] METRICS/DEBUGGER WINDOW
89
// [SECTION] DEBUG LOG WINDOW
90
// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, STACK TOOL)
91
92
*/
93
94
//-----------------------------------------------------------------------------
95
// DOCUMENTATION
96
//-----------------------------------------------------------------------------
97
98
/*
99
100
 MISSION STATEMENT
101
 =================
102
103
 - Easy to use to create code-driven and data-driven tools.
104
 - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
105
 - Easy to hack and improve.
106
 - Minimize setup and maintenance.
107
 - Minimize state storage on user side.
108
 - Minimize state synchronization.
109
 - Portable, minimize dependencies, run on target (consoles, phones, etc.).
110
 - Efficient runtime and memory consumption.
111
112
 Designed for developers and content-creators, not the typical end-user! Some of the current weaknesses includes:
113
114
 - Doesn't look fancy, doesn't animate.
115
 - Limited layout features, intricate layouts are typically crafted in code.
116
117
118
 END-USER GUIDE
119
 ==============
120
121
 - Double-click on title bar to collapse window.
122
 - Click upper right corner to close a window, available when 'bool* p_open' is passed to ImGui::Begin().
123
 - Click and drag on lower right corner to resize window (double-click to auto fit window to its contents).
124
 - Click and drag on any empty space to move window.
125
 - TAB/SHIFT+TAB to cycle through keyboard editable fields.
126
 - CTRL+Click on a slider or drag box to input value as text.
127
 - Use mouse wheel to scroll.
128
 - Text editor:
129
   - Hold SHIFT or use mouse to select text.
130
   - CTRL+Left/Right to word jump.
131
   - CTRL+Shift+Left/Right to select words.
132
   - CTRL+A or Double-Click to select all.
133
   - CTRL+X,CTRL+C,CTRL+V to use OS clipboard/
134
   - CTRL+Z,CTRL+Y to undo/redo.
135
   - ESCAPE to revert text to its original value.
136
   - Controls are automatically adjusted for OSX to match standard OSX text editing operations.
137
 - General Keyboard controls: enable with ImGuiConfigFlags_NavEnableKeyboard.
138
 - General Gamepad controls: enable with ImGuiConfigFlags_NavEnableGamepad. Download controller mapping PNG/PSD at http://dearimgui.org/controls_sheets
139
140
141
 PROGRAMMER GUIDE
142
 ================
143
144
 READ FIRST
145
 ----------
146
 - Remember to check the wonderful Wiki (https://github.com/ocornut/imgui/wiki)
147
 - Your code creates the UI, if your code doesn't run the UI is gone! The UI can be highly dynamic, there are no construction or
148
   destruction steps, less superfluous data retention on your side, less state duplication, less state synchronization, fewer bugs.
149
 - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
150
 - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
151
 - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
152
   You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki.
153
 - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
154
   For every application frame, your UI code will be called only once. This is in contrast to e.g. Unity's implementation of an IMGUI,
155
   where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
156
 - Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
157
 - This codebase is also optimized to yield decent performances with typical "Debug" builds settings.
158
 - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
159
   If you get an assert, read the messages and comments around the assert.
160
 - C++: this is a very C-ish codebase: we don't rely on C++11, we don't include any C++ headers, and ImGui:: is a namespace.
161
 - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
162
   See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
163
   However, imgui_internal.h can optionally export math operators for ImVec2/ImVec4, which we use in this codebase.
164
 - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction (avoid using it in your code!).
165
166
167
 HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
168
 ----------------------------------------------
169
 - Overwrite all the sources files except for imconfig.h (if you have modified your copy of imconfig.h)
170
 - Or maintain your own branch where you have imconfig.h modified as a top-most commit which you can regularly rebase over "master".
171
 - You can also use '#define IMGUI_USER_CONFIG "my_config_file.h" to redirect configuration to your own file.
172
 - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
173
   If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
174
   from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
175
   likely be a comment about it. Please report any issue to the GitHub page!
176
 - To find out usage of old API, you can add '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in your configuration file.
177
 - Try to keep your copy of Dear ImGui reasonably up to date.
178
179
180
 GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
181
 ---------------------------------------------------------------
182
 - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
183
 - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder.
184
 - Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system.
185
   It is recommended you build and statically link the .cpp files as part of your project and NOT as a shared library (DLL).
186
 - You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating Dear ImGui types with your own maths types.
187
 - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
188
 - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
189
   Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
190
   phases of your own application. All rendering information is stored into command-lists that you will retrieve after calling ImGui::Render().
191
 - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code.
192
 - If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder.
193
194
195
 HOW A SIMPLE APPLICATION MAY LOOK LIKE
196
 --------------------------------------
197
 EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder).
198
 The sub-folders in examples/ contain examples applications following this structure.
199
200
     // Application init: create a dear imgui context, setup some options, load fonts
201
     ImGui::CreateContext();
202
     ImGuiIO& io = ImGui::GetIO();
203
     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
204
     // TODO: Fill optional fields of the io structure later.
205
     // TODO: Load TTF/OTF fonts if you don't want to use the default font.
206
207
     // Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
208
     ImGui_ImplWin32_Init(hwnd);
209
     ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
210
211
     // Application main loop
212
     while (true)
213
     {
214
         // Feed inputs to dear imgui, start new frame
215
         ImGui_ImplDX11_NewFrame();
216
         ImGui_ImplWin32_NewFrame();
217
         ImGui::NewFrame();
218
219
         // Any application code here
220
         ImGui::Text("Hello, world!");
221
222
         // Render dear imgui into screen
223
         ImGui::Render();
224
         ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
225
         g_pSwapChain->Present(1, 0);
226
     }
227
228
     // Shutdown
229
     ImGui_ImplDX11_Shutdown();
230
     ImGui_ImplWin32_Shutdown();
231
     ImGui::DestroyContext();
232
233
 EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE
234
235
     // Application init: create a dear imgui context, setup some options, load fonts
236
     ImGui::CreateContext();
237
     ImGuiIO& io = ImGui::GetIO();
238
     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
239
     // TODO: Fill optional fields of the io structure later.
240
     // TODO: Load TTF/OTF fonts if you don't want to use the default font.
241
242
     // Build and load the texture atlas into a texture
243
     // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
244
     int width, height;
245
     unsigned char* pixels = NULL;
246
     io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
247
248
     // At this point you've got the texture data and you need to upload that to your graphic system:
249
     // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
250
     // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID.
251
     MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
252
     io.Fonts->SetTexID((void*)texture);
253
254
     // Application main loop
255
     while (true)
256
     {
257
        // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
258
        // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends)
259
        io.DeltaTime = 1.0f/60.0f;              // set the time elapsed since the previous frame (in seconds)
260
        io.DisplaySize.x = 1920.0f;             // set the current display width
261
        io.DisplaySize.y = 1280.0f;             // set the current display height here
262
        io.AddMousePosEvent(mouse_x, mouse_y);  // update mouse position
263
        io.AddMouseButtonEvent(0, mouse_b[0]);  // update mouse button states
264
        io.AddMouseButtonEvent(1, mouse_b[1]);  // update mouse button states
265
266
        // Call NewFrame(), after this point you can use ImGui::* functions anytime
267
        // (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere)
268
        ImGui::NewFrame();
269
270
        // Most of your application code here
271
        ImGui::Text("Hello, world!");
272
        MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
273
        MyGameRender(); // may use any Dear ImGui functions as well!
274
275
        // Render dear imgui, swap buffers
276
        // (You want to try calling EndFrame/Render as late as you can, to be able to use Dear ImGui in your own game rendering code)
277
        ImGui::EndFrame();
278
        ImGui::Render();
279
        ImDrawData* draw_data = ImGui::GetDrawData();
280
        MyImGuiRenderFunction(draw_data);
281
        SwapBuffers();
282
     }
283
284
     // Shutdown
285
     ImGui::DestroyContext();
286
287
 To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application,
288
 you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
289
 Please read the FAQ and example applications for details about this!
290
291
292
 HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
293
 ---------------------------------------------
294
 The backends in impl_impl_XXX.cpp files contain many working implementations of a rendering function.
295
296
    void MyImGuiRenderFunction(ImDrawData* draw_data)
297
    {
298
       // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
299
       // TODO: Setup texture sampling state: sample with bilinear filtering (NOT point/nearest filtering). Use 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines;' to allow point/nearest filtering.
300
       // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
301
       // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
302
       // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
303
       ImVec2 clip_off = draw_data->DisplayPos;
304
       for (int n = 0; n < draw_data->CmdListsCount; n++)
305
       {
306
          const ImDrawList* cmd_list = draw_data->CmdLists[n];
307
          const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;  // vertex buffer generated by Dear ImGui
308
          const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;   // index buffer generated by Dear ImGui
309
          for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
310
          {
311
             const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
312
             if (pcmd->UserCallback)
313
             {
314
                 pcmd->UserCallback(cmd_list, pcmd);
315
             }
316
             else
317
             {
318
                 // Project scissor/clipping rectangles into framebuffer space
319
                 ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
320
                 ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
321
                 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
322
                     continue;
323
324
                 // We are using scissoring to clip some objects. All low-level graphics API should support it.
325
                 // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
326
                 //   (some elements visible outside their bounds) but you can fix that once everything else works!
327
                 // - Clipping coordinates are provided in imgui coordinates space:
328
                 //   - For a given viewport, draw_data->DisplayPos == viewport->Pos and draw_data->DisplaySize == viewport->Size
329
                 //   - In a single viewport application, draw_data->DisplayPos == (0,0) and draw_data->DisplaySize == io.DisplaySize, but always use GetMainViewport()->Pos/Size instead of hardcoding those values.
330
                 //   - In the interest of supporting multi-viewport applications (see 'docking' branch on github),
331
                 //     always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
332
                 // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
333
                 MyEngineSetScissor(clip_min.x, clip_min.y, clip_max.x, clip_max.y);
334
335
                 // The texture for the draw call is specified by pcmd->GetTexID().
336
                 // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization.
337
                 MyEngineBindTexture((MyTexture*)pcmd->GetTexID());
338
339
                 // Render 'pcmd->ElemCount/3' indexed triangles.
340
                 // By default the indices ImDrawIdx are 16-bit, you can change them to 32-bit in imconfig.h if your engine doesn't support 16-bit indices.
341
                 MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer + pcmd->IdxOffset, vtx_buffer, pcmd->VtxOffset);
342
             }
343
          }
344
       }
345
    }
346
347
348
 USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS
349
 ------------------------------------------
350
 - The gamepad/keyboard navigation is fairly functional and keeps being improved.
351
 - Gamepad support is particularly useful to use Dear ImGui on a console system (e.g. PlayStation, Switch, Xbox) without a mouse!
352
 - The initial focus was to support game controllers, but keyboard is becoming increasingly and decently usable.
353
 - Keyboard:
354
    - Application: Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable.
355
    - When keyboard navigation is active (io.NavActive + ImGuiConfigFlags_NavEnableKeyboard),
356
      the io.WantCaptureKeyboard flag will be set. For more advanced uses, you may want to read from:
357
       - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
358
       - io.NavVisible: true when the navigation cursor is visible (and usually goes false when mouse is used).
359
       - or query focus information with e.g. IsWindowFocused(ImGuiFocusedFlags_AnyWindow), IsItemFocused() etc. functions.
360
      Please reach out if you think the game vs navigation input sharing could be improved.
361
 - Gamepad:
362
    - Application: Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad to enable.
363
    - Backend: Set io.BackendFlags |= ImGuiBackendFlags_HasGamepad + call io.AddKeyEvent/AddKeyAnalogEvent() with ImGuiKey_Gamepad_XXX keys.
364
      For analog values (0.0f to 1.0f), backend is responsible to handling a dead-zone and rescaling inputs accordingly.
365
      Backend code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.).
366
    - BEFORE 1.87, BACKENDS USED TO WRITE TO io.NavInputs[]. This is now obsolete. Please call io functions instead!
367
    - You can download PNG/PSD files depicting the gamepad controls for common controllers at: http://dearimgui.org/controls_sheets
368
    - If you need to share inputs between your game and the Dear ImGui interface, the easiest approach is to go all-or-nothing,
369
      with a buttons combo to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
370
 - Mouse:
371
    - PS4/PS5 users: Consider emulating a mouse cursor with DualShock4 touch pad or a spare analog stick as a mouse-emulation fallback.
372
    - Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + uSynergy.c (on your console/tablet/phone app) to share your PC mouse/keyboard.
373
    - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag.
374
      Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs dear imgui to move your mouse cursor along with navigation movements.
375
      When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved.
376
      When that happens your backend NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the backends in examples/ do that.
377
      (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, imgui will misbehave as it will see your mouse moving back and forth!)
378
      (In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want
379
       to set a boolean to ignore your other external mouse positions until the external source is moved again.)
380
381
382
 API BREAKING CHANGES
383
 ====================
384
385
 Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
386
 Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.
387
 When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
388
 You can read releases logs https://github.com/ocornut/imgui/releases for more details.
389
390
(Docking/Viewport Branch)
391
 - 2022/XX/XX (1.XX) - when multi-viewports are enabled, all positions will be in your natural OS coordinates space. It means that:
392
                        - reference to hard-coded positions such as in SetNextWindowPos(ImVec2(0,0)) are probably not what you want anymore.
393
                          you may use GetMainViewport()->Pos to offset hard-coded positions, e.g. SetNextWindowPos(GetMainViewport()->Pos)
394
                        - likewise io.MousePos and GetMousePos() will use OS coordinates.
395
                          If you query mouse positions to interact with non-imgui coordinates you will need to offset them, e.g. subtract GetWindowViewport()->Pos.
396
397
 - 2022/10/26 (1.89) - commented out redirecting OpenPopupContextItem() which was briefly the name of OpenPopupOnItemClick() from 1.77 to 1.79.
398
 - 2022/10/12 (1.89) - removed runtime patching of invalid "%f"/"%0.f" format strings for DragInt()/SliderInt(). This was obsoleted in 1.61 (May 2018). See 1.61 changelog for details.
399
 - 2022/09/26 (1.89) - renamed and merged keyboard modifiers key enums and flags into a same set. Kept inline redirection enums (will obsolete).
400
                         - ImGuiKey_ModCtrl  and ImGuiModFlags_Ctrl  -> ImGuiMod_Ctrl
401
                         - ImGuiKey_ModShift and ImGuiModFlags_Shift -> ImGuiMod_Shift
402
                         - ImGuiKey_ModAlt   and ImGuiModFlags_Alt   -> ImGuiMod_Alt
403
                         - ImGuiKey_ModSuper and ImGuiModFlags_Super -> ImGuiMod_Super
404
                       the ImGuiKey_ModXXX were introduced in 1.87 and mostly used by backends.
405
                       the ImGuiModFlags_XXX have been exposed in imgui.h but not really used by any public api only by third-party extensions.
406
                       exceptionally commenting out the older ImGuiKeyModFlags_XXX names ahead of obsolescence schedule to reduce confusion and because they were not meant to be used anyway.
407
 - 2022/09/20 (1.89) - ImGuiKey is now a typed enum, allowing ImGuiKey_XXX symbols to be named in debuggers.
408
                       this will require uses of legacy backend-dependent indices to be casted, e.g.
409
                          - with imgui_impl_glfw:  IsKeyPressed(GLFW_KEY_A) -> IsKeyPressed((ImGuiKey)GLFW_KEY_A);
410
                          - with imgui_impl_win32: IsKeyPressed('A')        -> IsKeyPressed((ImGuiKey)'A')
411
                          - etc. However if you are upgrading code you might well use the better, backend-agnostic IsKeyPressed(ImGuiKey_A) now!
412
 - 2022/09/12 (1.89) - removed the bizarre legacy default argument for 'TreePush(const void* ptr = NULL)', always pass a pointer value explicitly. NULL/nullptr is ok but require cast, e.g. TreePush((void*)nullptr);
413
 - 2022/09/05 (1.89) - commented out redirecting functions/enums names that were marked obsolete in 1.77 and 1.78 (June 2020):
414
                         - DragScalar(), DragScalarN(), DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
415
                         - SliderScalar(), SliderScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
416
                         - BeginPopupContextWindow(const char*, ImGuiMouseButton, bool) -> use BeginPopupContextWindow(const char*, ImGuiPopupFlags)
417
 - 2022/09/02 (1.89) - obsoleted using SetCursorPos()/SetCursorScreenPos() to extend parent window/cell boundaries.
418
                       this relates to when moving the cursor position beyond current boundaries WITHOUT submitting an item.
419
                         - previously this would make the window content size ~200x200:
420
                              Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();
421
                         - instead, please submit an item:
422
                              Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End();
423
                         - alternative:
424
                              Begin(...) + Dummy(ImVec2(200,200)) + End();
425
                         - content size is now only extended when submitting an item!
426
                         - with '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will now be detected and assert.
427
                         - without '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will silently be fixed until we obsolete it.
428
 - 2022/08/03 (1.89) - changed signature of ImageButton() function. Kept redirection function (will obsolete).
429
                        - added 'const char* str_id' parameter + removed 'int frame_padding = -1' parameter.
430
                        - old signature: bool ImageButton(ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), int frame_padding = -1, ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
431
                          - used the ImTextureID value to create an ID. This was inconsistent with other functions, led to ID conflicts, and caused problems with engines using transient ImTextureID values.
432
                          - had a FramePadding override which was inconsistent with other functions and made the already-long signature even longer.
433
                        - new signature: bool ImageButton(const char* str_id, ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
434
                          - requires an explicit identifier. You may still use e.g. PushID() calls and then pass an empty identifier.
435
                          - always uses style.FramePadding for padding, to be consistent with other buttons. You may use PushStyleVar() to alter this.
436
 - 2022/07/08 (1.89) - inputs: removed io.NavInputs[] and ImGuiNavInput enum (following 1.87 changes).
437
                        - Official backends from 1.87+                  -> no issue.
438
                        - Official backends from 1.60 to 1.86           -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need updating!
439
                        - Custom backends not writing to io.NavInputs[] -> no issue.
440
                        - Custom backends writing to io.NavInputs[]     -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need fixing!
441
                        - TL;DR: Backends should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values instead of filling io.NavInput[].
442
 - 2022/06/15 (1.88) - renamed IMGUI_DISABLE_METRICS_WINDOW to IMGUI_DISABLE_DEBUG_TOOLS for correctness. kept support for old define (will obsolete).
443
 - 2022/05/03 (1.88) - backends: osx: removed ImGui_ImplOSX_HandleEvent() from backend API in favor of backend automatically handling event capture. All ImGui_ImplOSX_HandleEvent() calls should be removed as they are now unnecessary.
444
 - 2022/04/05 (1.88) - inputs: renamed ImGuiKeyModFlags to ImGuiModFlags. Kept inline redirection enums (will obsolete). This was never used in public API functions but technically present in imgui.h and ImGuiIO.
445
 - 2022/01/20 (1.87) - inputs: reworded gamepad IO.
446
                        - Backend writing to io.NavInputs[]            -> backend should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values.
447
 - 2022/01/19 (1.87) - sliders, drags: removed support for legacy arithmetic operators (+,+-,*,/) when inputing text. This doesn't break any api/code but a feature that used to be accessible by end-users (which seemingly no one used).
448
 - 2022/01/17 (1.87) - inputs: reworked mouse IO.
449
                        - Backend writing to io.MousePos               -> backend should call io.AddMousePosEvent()
450
                        - Backend writing to io.MouseDown[]            -> backend should call io.AddMouseButtonEvent()
451
                        - Backend writing to io.MouseWheel             -> backend should call io.AddMouseWheelEvent()
452
                        - Backend writing to io.MouseHoveredViewport   -> backend should call io.AddMouseViewportEvent() [Docking branch w/ multi-viewports only]
453
                       note: for all calls to IO new functions, the Dear ImGui context should be bound/current.
454
                       read https://github.com/ocornut/imgui/issues/4921 for details.
455
 - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(). Removed GetKeyIndex(), now unecessary. All IsKeyXXX() functions now take ImGuiKey values. All features are still functional until IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Read Changelog and Release Notes for details.
456
                        - IsKeyPressed(MY_NATIVE_KEY_XXX)              -> use IsKeyPressed(ImGuiKey_XXX)
457
                        - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX))      -> use IsKeyPressed(ImGuiKey_XXX)
458
                        - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent() (+ call io.SetKeyEventNativeData() if you want legacy user code to stil function with legacy key codes).
459
                        - Backend writing to io.KeyCtrl, io.KeyShift.. -> backend should call io.AddKeyEvent() with ImGuiMod_XXX values. *IF YOU PULLED CODE BETWEEN 2021/01/10 and 2021/01/27: We used to have a io.AddKeyModsEvent() function which was now replaced by io.AddKeyEvent() with ImGuiMod_XXX values.*
460
                     - one case won't work with backward compatibility: if your custom backend used ImGuiKey as mock native indices (e.g. "io.KeyMap[ImGuiKey_A] = ImGuiKey_A") because those values are now larger than the legacy KeyDown[] array. Will assert.
461
                     - inputs: added ImGuiKey_ModCtrl/ImGuiKey_ModShift/ImGuiKey_ModAlt/ImGuiKey_ModSuper values to submit keyboard modifiers using io.AddKeyEvent(), instead of writing directly to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper.
462
 - 2022/01/05 (1.87) - inputs: renamed ImGuiKey_KeyPadEnter to ImGuiKey_KeypadEnter to align with new symbols. Kept redirection enum.
463
 - 2022/01/05 (1.87) - removed io.ImeSetInputScreenPosFn() in favor of more flexible io.SetPlatformImeDataFn(). Removed 'void* io.ImeWindowHandle' in favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
464
 - 2022/01/01 (1.87) - commented out redirecting functions/enums names that were marked obsolete in 1.69, 1.70, 1.71, 1.72 (March-July 2019)
465
                        - ImGui::SetNextTreeNodeOpen()        -> use ImGui::SetNextItemOpen()
466
                        - ImGui::GetContentRegionAvailWidth() -> use ImGui::GetContentRegionAvail().x
467
                        - ImGui::TreeAdvanceToLabelPos()      -> use ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetTreeNodeToLabelSpacing());
468
                        - ImFontAtlas::CustomRect             -> use ImFontAtlasCustomRect
469
                        - ImGuiColorEditFlags_RGB/HSV/HEX     -> use ImGuiColorEditFlags_DisplayRGB/HSV/Hex
470
 - 2021/12/20 (1.86) - backends: removed obsolete Marmalade backend (imgui_impl_marmalade.cpp) + example. Find last supported version at https://github.com/ocornut/imgui/wiki/Bindings
471
 - 2021/11/04 (1.86) - removed CalcListClipping() function. Prefer using ImGuiListClipper which can return non-contiguous ranges. Please open an issue if you think you really need this function.
472
 - 2021/08/23 (1.85) - removed GetWindowContentRegionWidth() function. keep inline redirection helper. can use 'GetWindowContentRegionMax().x - GetWindowContentRegionMin().x' instead for generally 'GetContentRegionAvail().x' is more useful.
473
 - 2021/07/26 (1.84) - commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019):
474
                        - ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList()
475
                        - ImFont::GlyphRangesBuilder  -> use ImFontGlyphRangesBuilder
476
 - 2021/05/19 (1.83) - backends: obsoleted direct access to ImDrawCmd::TextureId in favor of calling ImDrawCmd::GetTexID().
477
                        - if you are using official backends from the source tree: you have nothing to do.
478
                        - if you have copied old backend code or using your own: change access to draw_cmd->TextureId to draw_cmd->GetTexID().
479
 - 2021/03/12 (1.82) - upgraded ImDrawList::AddRect(), AddRectFilled(), PathRect() to use ImDrawFlags instead of ImDrawCornersFlags.
480
                        - ImDrawCornerFlags_TopLeft  -> use ImDrawFlags_RoundCornersTopLeft
481
                        - ImDrawCornerFlags_BotRight -> use ImDrawFlags_RoundCornersBottomRight
482
                        - ImDrawCornerFlags_None     -> use ImDrawFlags_RoundCornersNone etc.
483
                       flags now sanely defaults to 0 instead of 0x0F, consistent with all other flags in the API.
484
                       breaking: the default with rounding > 0.0f is now "round all corners" vs old implicit "round no corners":
485
                        - rounding == 0.0f + flags == 0 --> meant no rounding  --> unchanged (common use)
486
                        - rounding  > 0.0f + flags != 0 --> meant rounding     --> unchanged (common use)
487
                        - rounding == 0.0f + flags != 0 --> meant no rounding  --> unchanged (unlikely use)
488
                        - rounding  > 0.0f + flags == 0 --> meant no rounding  --> BREAKING (unlikely use): will now round all corners --> use ImDrawFlags_RoundCornersNone or rounding == 0.0f.
489
                       this ONLY matters for hard coded use of 0 + rounding > 0.0f. Use of named ImDrawFlags_RoundCornersNone (new) or ImDrawCornerFlags_None (old) are ok.
490
                       the old ImDrawCornersFlags used awkward default values of ~0 or 0xF (4 lower bits set) to signify "round all corners" and we sometimes encouraged using them as shortcuts.
491
                       legacy path still support use of hard coded ~0 or any value from 0x1 or 0xF. They will behave the same with legacy paths enabled (will assert otherwise).
492
 - 2021/03/11 (1.82) - removed redirecting functions/enums names that were marked obsolete in 1.66 (September 2018):
493
                        - ImGui::SetScrollHere()              -> use ImGui::SetScrollHereY()
494
 - 2021/03/11 (1.82) - clarified that ImDrawList::PathArcTo(), ImDrawList::PathArcToFast() won't render with radius < 0.0f. Previously it sorts of accidentally worked but would generally lead to counter-clockwise paths and have an effect on anti-aliasing.
495
 - 2021/03/10 (1.82) - upgraded ImDrawList::AddPolyline() and PathStroke() "bool closed" parameter to "ImDrawFlags flags". The matching ImDrawFlags_Closed value is guaranteed to always stay == 1 in the future.
496
 - 2021/02/22 (1.82) - (*undone in 1.84*) win32+mingw: Re-enabled IME functions by default even under MinGW. In July 2016, issue #738 had me incorrectly disable those default functions for MinGW. MinGW users should: either link with -limm32, either set their imconfig file  with '#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS'.
497
 - 2021/02/17 (1.82) - renamed rarely used style.CircleSegmentMaxError (old default = 1.60f) to style.CircleTessellationMaxError (new default = 0.30f) as the meaning of the value changed.
498
 - 2021/02/03 (1.81) - renamed ListBoxHeader(const char* label, ImVec2 size) to BeginListBox(). Kept inline redirection function (will obsolete).
499
                     - removed ListBoxHeader(const char* label, int items_count, int height_in_items = -1) in favor of specifying size. Kept inline redirection function (will obsolete).
500
                     - renamed ListBoxFooter() to EndListBox(). Kept inline redirection function (will obsolete).
501
 - 2021/01/26 (1.81) - removed ImGuiFreeType::BuildFontAtlas(). Kept inline redirection function. Prefer using '#define IMGUI_ENABLE_FREETYPE', but there's a runtime selection path available too. The shared extra flags parameters (very rarely used) are now stored in ImFontAtlas::FontBuilderFlags.
502
                     - renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags.
503
                     - renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API.
504
 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018):
505
                        - ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit().
506
                        - ImGuiCol_ModalWindowDarkening       -> use ImGuiCol_ModalWindowDimBg
507
                        - ImGuiInputTextCallback              -> use ImGuiTextEditCallback
508
                        - ImGuiInputTextCallbackData          -> use ImGuiTextEditCallbackData
509
 - 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete).
510
 - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added!
511
 - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API.
512
 - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures
513
 - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/.
514
 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018):
515
                        - io.RenderDrawListsFn pointer        -> use ImGui::GetDrawData() value and call the render function of your backend
516
                        - ImGui::IsAnyWindowFocused()         -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)
517
                        - ImGui::IsAnyWindowHovered()         -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
518
                        - ImGuiStyleVar_Count_                -> use ImGuiStyleVar_COUNT
519
                        - ImGuiMouseCursor_Count_             -> use ImGuiMouseCursor_COUNT
520
                      - removed redirecting functions names that were marked obsolete in 1.61 (May 2018):
521
                        - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision.
522
                        - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter.
523
 - 2020/10/05 (1.79) - removed ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using the ImGuiListClipper::Begin() function, with misleading edge cases (note: imgui_memory_editor <0.40 from imgui_club/ used this old clipper API. Update your copy if needed).
524
 - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently).
525
 - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton.
526
 - 2020/09/21 (1.79) - renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting the change from 1.77. For varieties of reason this is more self-explanatory.
527
 - 2020/09/21 (1.79) - removed return value from OpenPopupOnItemClick() - returned true on mouse release on an item - because it is inconsistent with other popup APIs and makes others misleading. It's also and unnecessary: you can use IsWindowAppearing() after BeginPopup() for a similar result.
528
 - 2020/09/17 (1.79) - removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. If you scaled this value after calling AddFontDefault(), this is now done automatically. It was also getting in the way of better font scaling, so let's get rid of it now!
529
 - 2020/08/17 (1.78) - obsoleted use of the trailing 'float power=1.0f' parameter for DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN(), VSliderFloat() and VSliderScalar().
530
                       replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags).
531
                       worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions:
532
                       - if you omitted the 'power' parameter (likely!), you are not affected.
533
                       - if you set the 'power' parameter to 1.0f (same as previous default value): 1/ your compiler may warn on float>int conversion, 2/ everything else will work. 3/ you can replace the 1.0f value with 0 to fix the warning, and be technically correct.
534
                       - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiSliderFlags_Logarithmic to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f.
535
                       see https://github.com/ocornut/imgui/issues/3361 for all details.
536
                       kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version was removed directly as they were most unlikely ever used.
537
                       for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.
538
                     - obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiSliderFlags_ReadOnly internal flag in the meantime.
539
 - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems.
540
 - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79]
541
 - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017.
542
 - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular().
543
 - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
544
 - 2019/12/17 (1.75) - [undid this change in 1.76] made Columns() limited to 64 columns by asserting above that limit. While the current code technically supports it, future code may not so we're putting the restriction ahead.
545
 - 2019/12/13 (1.75) - [imgui_internal.h] changed ImRect() default constructor initializes all fields to 0.0f instead of (FLT_MAX,FLT_MAX,-FLT_MAX,-FLT_MAX). If you used ImRect::Add() to create bounding boxes by adding multiple points into it, you may need to fix your initial value.
546
 - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
547
                       - ShowTestWindow()                    -> use ShowDemoWindow()
548
                       - IsRootWindowFocused()               -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
549
                       - IsRootWindowOrAnyChildFocused()     -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
550
                       - SetNextWindowContentWidth(w)        -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
551
                       - GetItemsLineHeightWithSpacing()     -> use GetFrameHeightWithSpacing()
552
                       - ImGuiCol_ChildWindowBg              -> use ImGuiCol_ChildBg
553
                       - ImGuiStyleVar_ChildWindowRounding   -> use ImGuiStyleVar_ChildRounding
554
                       - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
555
                       - IMGUI_DISABLE_TEST_WINDOWS          -> use IMGUI_DISABLE_DEMO_WINDOWS
556
 - 2019/12/08 (1.75) - obsoleted calling ImDrawList::PrimReserve() with a negative count (which was vaguely documented and rarely if ever used). Instead, we added an explicit PrimUnreserve() API.
557
 - 2019/12/06 (1.75) - removed implicit default parameter to IsMouseDragging(int button = 0) to be consistent with other mouse functions (none of the other functions have it).
558
 - 2019/11/21 (1.74) - ImFontAtlas::AddCustomRectRegular() now requires an ID larger than 0x110000 (instead of 0x10000) to conform with supporting Unicode planes 1-16 in a future update. ID below 0x110000 will now assert.
559
 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
560
 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
561
 - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
562
                       - Begin() [old 5 args version]        -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
563
                       - IsRootWindowOrAnyChildHovered()     -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
564
                       - AlignFirstTextHeightToWidgets()     -> use AlignTextToFramePadding()
565
                       - SetNextWindowPosCenter()            -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
566
                       - ImFont::Glyph                       -> use ImFontGlyph
567
 - 2019/10/14 (1.74) - inputs: Fixed a miscalculation in the keyboard/mouse "typematic" repeat delay/rate calculation, used by keys and e.g. repeating mouse buttons as well as the GetKeyPressedAmount() function.
568
                       if you were using a non-default value for io.KeyRepeatRate (previous default was 0.250), you can add +io.KeyRepeatDelay to it to compensate for the fix.
569
                       The function was triggering on: 0.0 and (delay+rate*N) where (N>=1). Fixed formula responds to (N>=0). Effectively it made io.KeyRepeatRate behave like it was set to (io.KeyRepeatRate + io.KeyRepeatDelay).
570
                       If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
571
 - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
572
 - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
573
 - 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names, or see how they were implemented until 1.71.
574
 - 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have
575
                       overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering.
576
                       This optimization is disabled if the parent window has no visual output, because it appears to be the most common situation leading to the creation of overlapping child windows.
577
                       Please reach out if you are affected.
578
 - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
579
 - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
580
 - 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now.
581
 - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
582
 - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
583
 - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
584
 - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with an arbitrarily small value!
585
 - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
586
 - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
587
 - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
588
 - 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects.
589
 - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
590
 - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
591
 - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
592
 - 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h.
593
                       If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
594
 - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
595
 - 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp.
596
                       NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
597
                       Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
598
 - 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent).
599
 - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
600
 - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
601
 - 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges [update 1.67 renamed to ConfigWindowsResizeFromEdges] to enable the feature.
602
 - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
603
 - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
604
 - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
605
 - 2018/06/08 (1.62) - examples: the imgui_impl_XXX files have been split to separate platform (Win32, GLFW, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan,  etc.).
606
                       old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports.
607
                       when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call.
608
                       in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
609
 - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
610
 - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
611
 - 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more.
612
                       If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
613
                       To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code.
614
                       If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to help you find them.
615
 - 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format",
616
                       consistent with other functions. Kept redirection functions (will obsolete).
617
 - 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value.
618
 - 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some backend ahead of merging the Nav branch).
619
 - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
620
 - 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically.
621
 - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
622
 - 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment.
623
 - 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display.
624
 - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
625
                       - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
626
                       - removed Shutdown() function, as DestroyContext() serve this purpose.
627
                       - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
628
                       - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
629
                       - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
630
 - 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths.
631
 - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
632
 - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
633
 - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
634
 - 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side.
635
 - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
636
 - 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags
637
 - 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame.
638
 - 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set.
639
 - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
640
 - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
641
                     - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
642
 - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
643
 - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
644
 - 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed.
645
 - 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up.
646
                       Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions.
647
 - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
648
 - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
649
 - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
650
 - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
651
 - 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency.
652
 - 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it.
653
 - 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details.
654
                       removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
655
                         IsItemHoveredRect()        --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
656
                         IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
657
                         IsMouseHoveringWindow()    --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
658
 - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
659
 - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
660
 - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
661
 - 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete).
662
 - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your backend if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
663
 - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
664
                     - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
665
                     - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
666
 - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
667
 - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix.
668
 - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
669
 - 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely.
670
 - 2017/08/13 (1.51) - renamed ImGuiCol_Column to ImGuiCol_Separator, ImGuiCol_ColumnHovered to ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive to ImGuiCol_SeparatorActive. Kept redirection enums (will obsolete).
671
 - 2017/08/11 (1.51) - renamed ImGuiSetCond_Always to ImGuiCond_Always, ImGuiSetCond_Once to ImGuiCond_Once, ImGuiSetCond_FirstUseEver to ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing to ImGuiCond_Appearing. Kept redirection enums (will obsolete).
672
 - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
673
 - 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu.
674
                     - changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options.
675
                     - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0))'
676
 - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
677
 - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
678
 - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
679
 - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetID() and use it instead of passing string to BeginChild().
680
 - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
681
 - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
682
 - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully, breakage should be minimal.
683
 - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
684
                       If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you, otherwise if <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
685
                       This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color:
686
                       ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); }
687
                       If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color.
688
 - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
689
 - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
690
 - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen).
691
 - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDrawList::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer.
692
 - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref GitHub issue #337).
693
 - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337)
694
 - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
695
 - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert.
696
 - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you.
697
 - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
698
 - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
699
 - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
700
                       GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side.
701
                       GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out!
702
 - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
703
 - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project.
704
 - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason
705
 - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure.
706
                       you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
707
 - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost.
708
                       this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
709
                     - if you are using a vanilla copy of one of the imgui_impl_XXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
710
                     - the signature of the io.RenderDrawListsFn handler has changed!
711
                       old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
712
                       new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
713
                         parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
714
                         ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
715
                         ImDrawCmd:  'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
716
                     - each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer.
717
                     - if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering!
718
                     - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
719
 - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
720
 - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
721
 - 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount.
722
 - 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence
723
 - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely used. Sorry!
724
 - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
725
 - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
726
 - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons.
727
 - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened.
728
 - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
729
 - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
730
 - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
731
 - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
732
 - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
733
 - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
734
 - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
735
 - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
736
 - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
737
 - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
738
 - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
739
 - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
740
 - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
741
 - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
742
 - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
743
 - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
744
 - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
745
 - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
746
                       - old:  const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
747
                       - new:  unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->SetTexID(YourTexIdentifier);
748
                       you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. It is now recommended that you sample the font texture with bilinear interpolation.
749
 - 2015/01/11 (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to call io.Fonts->SetTexID()
750
 - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
751
 - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
752
 - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
753
 - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
754
 - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
755
 - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
756
 - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly)
757
 - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
758
 - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
759
 - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
760
 - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
761
 - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
762
 - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
763
764
765
 FREQUENTLY ASKED QUESTIONS (FAQ)
766
 ================================
767
768
 Read all answers online:
769
   https://www.dearimgui.org/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url)
770
 Read all answers locally (with a text editor or ideally a Markdown viewer):
771
   docs/FAQ.md
772
 Some answers are copied down here to facilitate searching in code.
773
774
 Q&A: Basics
775
 ===========
776
777
 Q: Where is the documentation?
778
 A: This library is poorly documented at the moment and expects the user to be acquainted with C/C++.
779
    - Run the examples/ and explore them.
780
    - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
781
    - The demo covers most features of Dear ImGui, so you can read the code and see its output.
782
    - See documentation and comments at the top of imgui.cpp + effectively imgui.h.
783
    - Dozens of standalone example applications using e.g. OpenGL/DirectX are provided in the
784
      examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
785
    - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
786
    - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
787
    - Your programming IDE is your friend, find the type or function declaration to find comments
788
      associated with it.
789
790
 Q: What is this library called?
791
 Q: Which version should I get?
792
 >> This library is called "Dear ImGui", please don't call it "ImGui" :)
793
 >> See https://www.dearimgui.org/faq for details.
794
795
 Q&A: Integration
796
 ================
797
798
 Q: How to get started?
799
 A: Read 'PROGRAMMER GUIDE' above. Read examples/README.txt.
800
801
 Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?
802
 A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
803
 >> See https://www.dearimgui.org/faq for a fully detailed answer. You really want to read this.
804
805
 Q. How can I enable keyboard controls?
806
 Q: How can I use this without a mouse, without a keyboard or without a screen? (gamepad, input share, remote display)
807
 Q: I integrated Dear ImGui in my engine and little squares are showing instead of text...
808
 Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...
809
 Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...
810
 >> See https://www.dearimgui.org/faq
811
812
 Q&A: Usage
813
 ----------
814
815
 Q: About the ID Stack system..
816
   - Why is my widget not reacting when I click on it?
817
   - How can I have widgets with an empty label?
818
   - How can I have multiple widgets with the same label?
819
   - How can I have multiple windows with the same label?
820
 Q: How can I display an image? What is ImTextureID, how does it work?
821
 Q: How can I use my own math types instead of ImVec2/ImVec4?
822
 Q: How can I interact with standard C++ types (such as std::string and std::vector)?
823
 Q: How can I display custom shapes? (using low-level ImDrawList API)
824
 >> See https://www.dearimgui.org/faq
825
826
 Q&A: Fonts, Text
827
 ================
828
829
 Q: How should I handle DPI in my application?
830
 Q: How can I load a different font than the default?
831
 Q: How can I easily use icons in my application?
832
 Q: How can I load multiple fonts?
833
 Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
834
 >> See https://www.dearimgui.org/faq and https://github.com/ocornut/imgui/edit/master/docs/FONTS.md
835
836
 Q&A: Concerns
837
 =============
838
839
 Q: Who uses Dear ImGui?
840
 Q: Can you create elaborate/serious tools with Dear ImGui?
841
 Q: Can you reskin the look of Dear ImGui?
842
 Q: Why using C++ (as opposed to C)?
843
 >> See https://www.dearimgui.org/faq
844
845
 Q&A: Community
846
 ==============
847
848
 Q: How can I help?
849
 A: - Businesses: please reach out to "contact AT dearimgui.com" if you work in a place using Dear ImGui!
850
      We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
851
      This is among the most useful thing you can do for Dear ImGui. With increased funding, we can hire more people working on this project.
852
    - Individuals: you can support continued development via PayPal donations. See README.
853
    - If you are experienced with Dear ImGui and C++, look at the GitHub issues, look at the Wiki, read docs/TODO.txt
854
      and see how you want to help and can help!
855
    - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
856
      You may post screenshot or links in the gallery threads. Visuals are ideal as they inspire other programmers.
857
      But even without visuals, disclosing your use of dear imgui helps the library grow credibility, and help other teams and programmers with taking decisions.
858
    - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on GitHub or privately).
859
860
*/
861
862
//-------------------------------------------------------------------------
863
// [SECTION] INCLUDES
864
//-------------------------------------------------------------------------
865
866
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
867
#define _CRT_SECURE_NO_WARNINGS
868
#endif
869
870
#include "imgui.h"
871
#ifndef IMGUI_DISABLE
872
873
#ifndef IMGUI_DEFINE_MATH_OPERATORS
874
#define IMGUI_DEFINE_MATH_OPERATORS
875
#endif
876
#include "imgui_internal.h"
877
878
// System includes
879
#include <stdio.h>      // vsnprintf, sscanf, printf
880
#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
881
#include <stddef.h>     // intptr_t
882
#else
883
#include <stdint.h>     // intptr_t
884
#endif
885
886
// [Windows] On non-Visual Studio compilers, we default to IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS unless explicitly enabled
887
#if defined(_WIN32) && !defined(_MSC_VER) && !defined(IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
888
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
889
#endif
890
891
// [Windows] OS specific includes (optional)
892
#if defined(_WIN32) && defined(IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
893
#define IMGUI_DISABLE_WIN32_FUNCTIONS
894
#endif
895
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
896
#ifndef WIN32_LEAN_AND_MEAN
897
#define WIN32_LEAN_AND_MEAN
898
#endif
899
#ifndef NOMINMAX
900
#define NOMINMAX
901
#endif
902
#ifndef __MINGW32__
903
#include <Windows.h>        // _wfopen, OpenClipboard
904
#else
905
#include <windows.h>
906
#endif
907
#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) // UWP doesn't have all Win32 functions
908
#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
909
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
910
#endif
911
#endif
912
913
// [Apple] OS specific includes
914
#if defined(__APPLE__)
915
#include <TargetConditionals.h>
916
#endif
917
918
// Visual Studio warnings
919
#ifdef _MSC_VER
920
#pragma warning (disable: 4127)             // condition expression is constant
921
#pragma warning (disable: 4996)             // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
922
#if defined(_MSC_VER) && _MSC_VER >= 1922   // MSVC 2019 16.2 or later
923
#pragma warning (disable: 5054)             // operator '|': deprecated between enumerations of different types
924
#endif
925
#pragma warning (disable: 26451)            // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to an 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2).
926
#pragma warning (disable: 26495)            // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).
927
#pragma warning (disable: 26812)            // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
928
#endif
929
930
// Clang/GCC warnings with -Weverything
931
#if defined(__clang__)
932
#if __has_warning("-Wunknown-warning-option")
933
#pragma clang diagnostic ignored "-Wunknown-warning-option"         // warning: unknown warning group 'xxx'                      // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!
934
#endif
935
#pragma clang diagnostic ignored "-Wunknown-pragmas"                // warning: unknown warning group 'xxx'
936
#pragma clang diagnostic ignored "-Wold-style-cast"                 // warning: use of old-style cast                            // yes, they are more terse.
937
#pragma clang diagnostic ignored "-Wfloat-equal"                    // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
938
#pragma clang diagnostic ignored "-Wformat-nonliteral"              // warning: format string is not a string literal            // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
939
#pragma clang diagnostic ignored "-Wexit-time-destructors"          // warning: declaration requires an exit-time destructor     // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.
940
#pragma clang diagnostic ignored "-Wglobal-constructors"            // warning: declaration requires a global destructor         // similar to above, not sure what the exact difference is.
941
#pragma clang diagnostic ignored "-Wsign-conversion"                // warning: implicit conversion changes signedness
942
#pragma clang diagnostic ignored "-Wformat-pedantic"                // warning: format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic.
943
#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast"       // warning: cast to 'void *' from smaller integer type 'int'
944
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"  // warning: zero as null pointer constant                    // some standard header variations use #define NULL 0
945
#pragma clang diagnostic ignored "-Wdouble-promotion"               // warning: implicit conversion from 'float' to 'double' when passing argument to function  // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
946
#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion"  // warning: implicit conversion from 'xxx' to 'float' may lose precision
947
#elif defined(__GNUC__)
948
// We disable -Wpragmas because GCC doesn't provide a has_warning equivalent and some forks/patches may not follow the warning/version association.
949
#pragma GCC diagnostic ignored "-Wpragmas"                  // warning: unknown option after '#pragma GCC diagnostic' kind
950
#pragma GCC diagnostic ignored "-Wunused-function"          // warning: 'xxxx' defined but not used
951
#pragma GCC diagnostic ignored "-Wint-to-pointer-cast"      // warning: cast to pointer from integer of different size
952
#pragma GCC diagnostic ignored "-Wformat"                   // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
953
#pragma GCC diagnostic ignored "-Wdouble-promotion"         // warning: implicit conversion from 'float' to 'double' when passing argument to function
954
#pragma GCC diagnostic ignored "-Wconversion"               // warning: conversion to 'xxxx' from 'xxxx' may alter its value
955
#pragma GCC diagnostic ignored "-Wformat-nonliteral"        // warning: format not a string literal, format string not checked
956
#pragma GCC diagnostic ignored "-Wstrict-overflow"          // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
957
#pragma GCC diagnostic ignored "-Wclass-memaccess"          // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
958
#endif
959
960
// Debug options
961
7.51k
#define IMGUI_DEBUG_NAV_SCORING     0   // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL
962
#define IMGUI_DEBUG_NAV_RECTS       0   // Display the reference navigation rectangle for each window
963
#define IMGUI_DEBUG_INI_SETTINGS    0   // Save additional comments in .ini file (particularly helps for Docking, but makes saving slower)
964
965
// When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch.
966
static const float NAV_WINDOWING_HIGHLIGHT_DELAY            = 0.20f;    // Time before the highlight and screen dimming starts fading in
967
static const float NAV_WINDOWING_LIST_APPEAR_DELAY          = 0.15f;    // Time before the window list starts to appear
968
969
// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by backend)
970
static const float WINDOWS_HOVER_PADDING                    = 4.0f;     // Extend outside window for hovering/resizing (maxxed with TouchPadding) and inside windows for borders. Affect FindHoveredWindow().
971
static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f;    // Reduce visual noise by only highlighting the border after a certain time.
972
static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER    = 0.70f;    // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved.
973
974
// Docking
975
static const float DOCKING_TRANSPARENT_PAYLOAD_ALPHA        = 0.50f;    // For use with io.ConfigDockingTransparentPayload. Apply to Viewport _or_ WindowBg in host viewport.
976
static const float DOCKING_SPLITTER_SIZE                    = 2.0f;
977
978
//-------------------------------------------------------------------------
979
// [SECTION] FORWARD DECLARATIONS
980
//-------------------------------------------------------------------------
981
982
static void             SetCurrentWindow(ImGuiWindow* window);
983
static void             FindHoveredWindow();
984
static ImGuiWindow*     CreateNewWindow(const char* name, ImGuiWindowFlags flags);
985
static ImVec2           CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
986
987
static void             AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list);
988
static void             AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
989
990
// Settings
991
static void             WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
992
static void*            WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
993
static void             WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
994
static void             WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
995
static void             WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
996
997
// Platform Dependents default implementation for IO functions
998
static const char*      GetClipboardTextFn_DefaultImpl(void* user_data);
999
static void             SetClipboardTextFn_DefaultImpl(void* user_data, const char* text);
1000
static void             SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data);
1001
1002
namespace ImGui
1003
{
1004
// Navigation
1005
static void             NavUpdate();
1006
static void             NavUpdateWindowing();
1007
static void             NavUpdateWindowingOverlay();
1008
static void             NavUpdateCancelRequest();
1009
static void             NavUpdateCreateMoveRequest();
1010
static void             NavUpdateCreateTabbingRequest();
1011
static float            NavUpdatePageUpPageDown();
1012
static inline void      NavUpdateAnyRequestFlag();
1013
static void             NavUpdateCreateWrappingRequest();
1014
static void             NavEndFrame();
1015
static bool             NavScoreItem(ImGuiNavItemData* result);
1016
static void             NavApplyItemToResult(ImGuiNavItemData* result);
1017
static void             NavProcessItem();
1018
static void             NavProcessItemForTabbingRequest(ImGuiID id);
1019
static ImVec2           NavCalcPreferredRefPos();
1020
static void             NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
1021
static ImGuiWindow*     NavRestoreLastChildNavWindow(ImGuiWindow* window);
1022
static void             NavRestoreLayer(ImGuiNavLayer layer);
1023
static void             NavRestoreHighlightAfterMove();
1024
static int              FindWindowFocusIndex(ImGuiWindow* window);
1025
1026
// Error Checking and Debug Tools
1027
static void             ErrorCheckNewFrameSanityChecks();
1028
static void             ErrorCheckEndFrameSanityChecks();
1029
static void             UpdateDebugToolItemPicker();
1030
static void             UpdateDebugToolStackQueries();
1031
1032
// Inputs
1033
static void             UpdateKeyboardInputs();
1034
static void             UpdateMouseInputs();
1035
static void             UpdateMouseWheel();
1036
static void             UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt);
1037
1038
// Misc
1039
static void             UpdateSettings();
1040
static bool             UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect);
1041
static void             RenderWindowOuterBorders(ImGuiWindow* window);
1042
static void             RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size);
1043
static void             RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
1044
static void             RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col);
1045
static void             RenderDimmedBackgrounds();
1046
static ImGuiWindow*     FindBlockingModal(ImGuiWindow* window);
1047
1048
// Viewports
1049
const ImGuiID           IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111; // Using an arbitrary constant instead of e.g. ImHashStr("ViewportDefault", 0); so it's easier to spot in the debugger. The exact value doesn't matter.
1050
static ImGuiViewportP*  AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& platform_pos, const ImVec2& size, ImGuiViewportFlags flags);
1051
static void             DestroyViewport(ImGuiViewportP* viewport);
1052
static void             UpdateViewportsNewFrame();
1053
static void             UpdateViewportsEndFrame();
1054
static void             WindowSelectViewport(ImGuiWindow* window);
1055
static void             WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack);
1056
static bool             UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* host_viewport);
1057
static bool             UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window);
1058
static bool             GetWindowAlwaysWantOwnViewport(ImGuiWindow* window);
1059
static int              FindPlatformMonitorForPos(const ImVec2& pos);
1060
static int              FindPlatformMonitorForRect(const ImRect& r);
1061
static void             UpdateViewportPlatformMonitor(ImGuiViewportP* viewport);
1062
1063
}
1064
1065
//-----------------------------------------------------------------------------
1066
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
1067
//-----------------------------------------------------------------------------
1068
1069
// DLL users:
1070
// - Heaps and globals are not shared across DLL boundaries!
1071
// - You will need to call SetCurrentContext() + SetAllocatorFunctions() for each static/DLL boundary you are calling from.
1072
// - Same applies for hot-reloading mechanisms that are reliant on reloading DLL (note that many hot-reloading mechanisms work without DLL).
1073
// - Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility.
1074
// - Confused? In a debugger: add GImGui to your watch window and notice how its value changes depending on your current location (which DLL boundary you are in).
1075
1076
// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
1077
// - ImGui::CreateContext() will automatically set this pointer if it is NULL.
1078
//   Change to a different context by calling ImGui::SetCurrentContext().
1079
// - Important: Dear ImGui functions are not thread-safe because of this pointer.
1080
//   If you want thread-safety to allow N threads to access N different contexts:
1081
//   - Change this variable to use thread local storage so each thread can refer to a different context, in your imconfig.h:
1082
//         struct ImGuiContext;
1083
//         extern thread_local ImGuiContext* MyImGuiTLS;
1084
//         #define GImGui MyImGuiTLS
1085
//     And then define MyImGuiTLS in one of your cpp files. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword.
1086
//   - Future development aims to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
1087
//   - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from a different namespace.
1088
// - DLL users: read comments above.
1089
#ifndef GImGui
1090
ImGuiContext*   GImGui = NULL;
1091
#endif
1092
1093
// Memory Allocator functions. Use SetAllocatorFunctions() to change them.
1094
// - You probably don't want to modify that mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
1095
// - DLL users: read comments above.
1096
#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
1097
1.20k
static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); return malloc(size); }
1098
1.15k
static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); free(ptr); }
1099
#else
1100
static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
1101
static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
1102
#endif
1103
static ImGuiMemAllocFunc    GImAllocatorAllocFunc = MallocWrapper;
1104
static ImGuiMemFreeFunc     GImAllocatorFreeFunc = FreeWrapper;
1105
static void*                GImAllocatorUserData = NULL;
1106
1107
//-----------------------------------------------------------------------------
1108
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
1109
//-----------------------------------------------------------------------------
1110
1111
ImGuiStyle::ImGuiStyle()
1112
1
{
1113
1
    Alpha                   = 1.0f;             // Global alpha applies to everything in Dear ImGui.
1114
1
    DisabledAlpha           = 0.60f;            // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha.
1115
1
    WindowPadding           = ImVec2(8,8);      // Padding within a window
1116
1
    WindowRounding          = 0.0f;             // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended.
1117
1
    WindowBorderSize        = 1.0f;             // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1118
1
    WindowMinSize           = ImVec2(32,32);    // Minimum window size
1119
1
    WindowTitleAlign        = ImVec2(0.0f,0.5f);// Alignment for title bar text
1120
1
    WindowMenuButtonPosition= ImGuiDir_Left;    // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
1121
1
    ChildRounding           = 0.0f;             // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
1122
1
    ChildBorderSize         = 1.0f;             // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1123
1
    PopupRounding           = 0.0f;             // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
1124
1
    PopupBorderSize         = 1.0f;             // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1125
1
    FramePadding            = ImVec2(4,3);      // Padding within a framed rectangle (used by most widgets)
1126
1
    FrameRounding           = 0.0f;             // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
1127
1
    FrameBorderSize         = 0.0f;             // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
1128
1
    ItemSpacing             = ImVec2(8,4);      // Horizontal and vertical spacing between widgets/lines
1129
1
    ItemInnerSpacing        = ImVec2(4,4);      // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
1130
1
    CellPadding             = ImVec2(4,2);      // Padding within a table cell
1131
1
    TouchExtraPadding       = ImVec2(0,0);      // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
1132
1
    IndentSpacing           = 21.0f;            // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
1133
1
    ColumnsMinSpacing       = 6.0f;             // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
1134
1
    ScrollbarSize           = 14.0f;            // Width of the vertical scrollbar, Height of the horizontal scrollbar
1135
1
    ScrollbarRounding       = 9.0f;             // Radius of grab corners rounding for scrollbar
1136
1
    GrabMinSize             = 12.0f;            // Minimum width/height of a grab box for slider/scrollbar
1137
1
    GrabRounding            = 0.0f;             // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
1138
1
    LogSliderDeadzone       = 4.0f;             // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
1139
1
    TabRounding             = 4.0f;             // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
1140
1
    TabBorderSize           = 0.0f;             // Thickness of border around tabs.
1141
1
    TabMinWidthForCloseButton = 0.0f;           // Minimum width for close button to appear on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected.
1142
1
    ColorButtonPosition     = ImGuiDir_Right;   // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
1143
1
    ButtonTextAlign         = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
1144
1
    SelectableTextAlign     = ImVec2(0.0f,0.0f);// Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line.
1145
1
    DisplayWindowPadding    = ImVec2(19,19);    // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows.
1146
1
    DisplaySafeAreaPadding  = ImVec2(3,3);      // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows.
1147
1
    MouseCursorScale        = 1.0f;             // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
1148
1
    AntiAliasedLines        = true;             // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU.
1149
1
    AntiAliasedLinesUseTex  = true;             // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering).
1150
1
    AntiAliasedFill         = true;             // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.).
1151
1
    CurveTessellationTol    = 1.25f;            // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
1152
1
    CircleTessellationMaxError = 0.30f;         // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry.
1153
1154
    // Default theme
1155
1
    ImGui::StyleColorsDark(this);
1156
1
}
1157
1158
// To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you.
1159
// Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times.
1160
void ImGuiStyle::ScaleAllSizes(float scale_factor)
1161
0
{
1162
0
    WindowPadding = ImFloor(WindowPadding * scale_factor);
1163
0
    WindowRounding = ImFloor(WindowRounding * scale_factor);
1164
0
    WindowMinSize = ImFloor(WindowMinSize * scale_factor);
1165
0
    ChildRounding = ImFloor(ChildRounding * scale_factor);
1166
0
    PopupRounding = ImFloor(PopupRounding * scale_factor);
1167
0
    FramePadding = ImFloor(FramePadding * scale_factor);
1168
0
    FrameRounding = ImFloor(FrameRounding * scale_factor);
1169
0
    ItemSpacing = ImFloor(ItemSpacing * scale_factor);
1170
0
    ItemInnerSpacing = ImFloor(ItemInnerSpacing * scale_factor);
1171
0
    CellPadding = ImFloor(CellPadding * scale_factor);
1172
0
    TouchExtraPadding = ImFloor(TouchExtraPadding * scale_factor);
1173
0
    IndentSpacing = ImFloor(IndentSpacing * scale_factor);
1174
0
    ColumnsMinSpacing = ImFloor(ColumnsMinSpacing * scale_factor);
1175
0
    ScrollbarSize = ImFloor(ScrollbarSize * scale_factor);
1176
0
    ScrollbarRounding = ImFloor(ScrollbarRounding * scale_factor);
1177
0
    GrabMinSize = ImFloor(GrabMinSize * scale_factor);
1178
0
    GrabRounding = ImFloor(GrabRounding * scale_factor);
1179
0
    LogSliderDeadzone = ImFloor(LogSliderDeadzone * scale_factor);
1180
0
    TabRounding = ImFloor(TabRounding * scale_factor);
1181
0
    TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImFloor(TabMinWidthForCloseButton * scale_factor) : FLT_MAX;
1182
0
    DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor);
1183
0
    DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor);
1184
0
    MouseCursorScale = ImFloor(MouseCursorScale * scale_factor);
1185
0
}
1186
1187
ImGuiIO::ImGuiIO()
1188
1
{
1189
    // Most fields are initialized with zero
1190
1
    memset(this, 0, sizeof(*this));
1191
1
    IM_STATIC_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT);
1192
1193
    // Settings
1194
1
    ConfigFlags = ImGuiConfigFlags_None;
1195
1
    BackendFlags = ImGuiBackendFlags_None;
1196
1
    DisplaySize = ImVec2(-1.0f, -1.0f);
1197
1
    DeltaTime = 1.0f / 60.0f;
1198
1
    IniSavingRate = 5.0f;
1199
1
    IniFilename = "imgui.ini"; // Important: "imgui.ini" is relative to current working dir, most apps will want to lock this to an absolute path (e.g. same path as executables).
1200
1
    LogFilename = "imgui_log.txt";
1201
1
    MouseDoubleClickTime = 0.30f;
1202
1
    MouseDoubleClickMaxDist = 6.0f;
1203
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1204
    for (int i = 0; i < ImGuiKey_COUNT; i++)
1205
        KeyMap[i] = -1;
1206
#endif
1207
1
    KeyRepeatDelay = 0.275f;
1208
1
    KeyRepeatRate = 0.050f;
1209
1
    HoverDelayNormal = 0.30f;
1210
1
    HoverDelayShort = 0.10f;
1211
1
    UserData = NULL;
1212
1213
1
    Fonts = NULL;
1214
1
    FontGlobalScale = 1.0f;
1215
1
    FontDefault = NULL;
1216
1
    FontAllowUserScaling = false;
1217
1
    DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
1218
1219
    // Docking options (when ImGuiConfigFlags_DockingEnable is set)
1220
1
    ConfigDockingNoSplit = false;
1221
1
    ConfigDockingWithShift = false;
1222
1
    ConfigDockingAlwaysTabBar = false;
1223
1
    ConfigDockingTransparentPayload = false;
1224
1225
    // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set)
1226
1
    ConfigViewportsNoAutoMerge = false;
1227
1
    ConfigViewportsNoTaskBarIcon = false;
1228
1
    ConfigViewportsNoDecoration = true;
1229
1
    ConfigViewportsNoDefaultParent = false;
1230
1231
    // Miscellaneous options
1232
1
    MouseDrawCursor = false;
1233
#ifdef __APPLE__
1234
    ConfigMacOSXBehaviors = true;  // Set Mac OS X style defaults based on __APPLE__ compile time flag
1235
#else
1236
1
    ConfigMacOSXBehaviors = false;
1237
1
#endif
1238
1
    ConfigInputTrickleEventQueue = true;
1239
1
    ConfigInputTextCursorBlink = true;
1240
1
    ConfigInputTextEnterKeepActive = false;
1241
1
    ConfigDragClickToInputText = false;
1242
1
    ConfigWindowsResizeFromEdges = true;
1243
1
    ConfigWindowsMoveFromTitleBarOnly = false;
1244
1
    ConfigMemoryCompactTimer = 60.0f;
1245
1246
    // Platform Functions
1247
1
    BackendPlatformName = BackendRendererName = NULL;
1248
1
    BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
1249
1
    GetClipboardTextFn = GetClipboardTextFn_DefaultImpl;   // Platform dependent default implementations
1250
1
    SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
1251
1
    ClipboardUserData = NULL;
1252
1
    SetPlatformImeDataFn = SetPlatformImeDataFn_DefaultImpl;
1253
1254
    // Input (NB: we already have memset zero the entire structure!)
1255
1
    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1256
1
    MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
1257
1
    MouseDragThreshold = 6.0f;
1258
6
    for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
1259
141
    for (int i = 0; i < IM_ARRAYSIZE(KeysData); i++) { KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; }
1260
1
    AppAcceptingEvents = true;
1261
1
    BackendUsingLegacyKeyArrays = (ImS8)-1;
1262
1
    BackendUsingLegacyNavInputArray = true; // assume using legacy array until proven wrong
1263
1
}
1264
1265
// Pass in translated ASCII characters for text input.
1266
// - with glfw you can get those from the callback set in glfwSetCharCallback()
1267
// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
1268
// FIXME: Should in theory be called "AddCharacterEvent()" to be consistent with new API
1269
void ImGuiIO::AddInputCharacter(unsigned int c)
1270
1.01k
{
1271
1.01k
    ImGuiContext& g = *GImGui;
1272
1.01k
    IM_ASSERT(&g.IO == this && "Can only add events to current context.");
1273
1.01k
    if (c == 0 || !AppAcceptingEvents)
1274
659
        return;
1275
1276
359
    ImGuiInputEvent e;
1277
359
    e.Type = ImGuiInputEventType_Text;
1278
359
    e.Source = ImGuiInputSource_Keyboard;
1279
359
    e.Text.Char = c;
1280
359
    g.InputEventsQueue.push_back(e);
1281
359
}
1282
1283
// UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
1284
// we should save the high surrogate.
1285
void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
1286
250
{
1287
250
    if ((c == 0 && InputQueueSurrogate == 0) || !AppAcceptingEvents)
1288
22
        return;
1289
1290
228
    if ((c & 0xFC00) == 0xD800) // High surrogate, must save
1291
118
    {
1292
118
        if (InputQueueSurrogate != 0)
1293
51
            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1294
118
        InputQueueSurrogate = c;
1295
118
        return;
1296
118
    }
1297
1298
110
    ImWchar cp = c;
1299
110
    if (InputQueueSurrogate != 0)
1300
63
    {
1301
63
        if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
1302
27
        {
1303
27
            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1304
27
        }
1305
36
        else
1306
36
        {
1307
36
#if IM_UNICODE_CODEPOINT_MAX == 0xFFFF
1308
36
            cp = IM_UNICODE_CODEPOINT_INVALID; // Codepoint will not fit in ImWchar
1309
#else
1310
            cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
1311
#endif
1312
36
        }
1313
1314
63
        InputQueueSurrogate = 0;
1315
63
    }
1316
110
    AddInputCharacter((unsigned)cp);
1317
110
}
1318
1319
void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
1320
0
{
1321
0
    if (!AppAcceptingEvents)
1322
0
        return;
1323
0
    while (*utf8_chars != 0)
1324
0
    {
1325
0
        unsigned int c = 0;
1326
0
        utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
1327
0
        AddInputCharacter(c);
1328
0
    }
1329
0
}
1330
1331
// FIXME: Perhaps we could clear queued events as well?
1332
void ImGuiIO::ClearInputCharacters()
1333
778
{
1334
778
    InputQueueCharacters.resize(0);
1335
778
}
1336
1337
// FIXME: Perhaps we could clear queued events as well?
1338
void ImGuiIO::ClearInputKeys()
1339
842
{
1340
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1341
    memset(KeysDown, 0, sizeof(KeysDown));
1342
#endif
1343
118k
    for (int n = 0; n < IM_ARRAYSIZE(KeysData); n++)
1344
117k
    {
1345
117k
        KeysData[n].Down             = false;
1346
117k
        KeysData[n].DownDuration     = -1.0f;
1347
117k
        KeysData[n].DownDurationPrev = -1.0f;
1348
117k
    }
1349
842
    KeyCtrl = KeyShift = KeyAlt = KeySuper = false;
1350
842
    KeyMods = ImGuiMod_None;
1351
842
    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1352
5.05k
    for (int n = 0; n < IM_ARRAYSIZE(MouseDown); n++)
1353
4.21k
    {
1354
4.21k
        MouseDown[n] = false;
1355
4.21k
        MouseDownDuration[n] = MouseDownDurationPrev[n] = -1.0f;
1356
4.21k
    }
1357
842
    MouseWheel = MouseWheelH = 0.0f;
1358
842
}
1359
1360
static ImGuiInputEvent* FindLatestInputEvent(ImGuiInputEventType type, int arg = -1)
1361
1.48k
{
1362
1.48k
    ImGuiContext& g = *GImGui;
1363
2.20k
    for (int n = g.InputEventsQueue.Size - 1; n >= 0; n--)
1364
1.42k
    {
1365
1.42k
        ImGuiInputEvent* e = &g.InputEventsQueue[n];
1366
1.42k
        if (e->Type != type)
1367
665
            continue;
1368
761
        if (type == ImGuiInputEventType_Key && e->Key.Key != arg)
1369
2
            continue;
1370
759
        if (type == ImGuiInputEventType_MouseButton && e->MouseButton.Button != arg)
1371
54
            continue;
1372
705
        return e;
1373
759
    }
1374
777
    return NULL;
1375
1.48k
}
1376
1377
// Queue a new key down/up event.
1378
// - ImGuiKey key:       Translated key (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character)
1379
// - bool down:          Is the key down? use false to signify a key release.
1380
// - float analog_value: 0.0f..1.0f
1381
void ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value)
1382
45
{
1383
    //if (e->Down) { IMGUI_DEBUG_LOG_IO("AddKeyEvent() Key='%s' %d, NativeKeycode = %d, NativeScancode = %d\n", ImGui::GetKeyName(e->Key), e->Down, e->NativeKeycode, e->NativeScancode); }
1384
45
    if (key == ImGuiKey_None || !AppAcceptingEvents)
1385
0
        return;
1386
45
    ImGuiContext& g = *GImGui;
1387
45
    IM_ASSERT(&g.IO == this && "Can only add events to current context.");
1388
45
    IM_ASSERT(ImGui::IsNamedKeyOrModKey(key)); // Backend needs to pass a valid ImGuiKey_ constant. 0..511 values are legacy native key codes which are not accepted by this API.
1389
45
    IM_ASSERT(!ImGui::IsAliasKey(key)); // Backend cannot submit ImGuiKey_MouseXXX values they are automatically inferred from AddMouseXXX() events.
1390
45
    IM_ASSERT(key != ImGuiMod_Shortcut); // We could easily support the translation here but it seems saner to not accept it (TestEngine perform a translation itself)
1391
1392
    // Verify that backend isn't mixing up using new io.AddKeyEvent() api and old io.KeysDown[] + io.KeyMap[] data.
1393
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1394
    IM_ASSERT((BackendUsingLegacyKeyArrays == -1 || BackendUsingLegacyKeyArrays == 0) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1395
    if (BackendUsingLegacyKeyArrays == -1)
1396
        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
1397
            IM_ASSERT(KeyMap[n] == -1 && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1398
    BackendUsingLegacyKeyArrays = 0;
1399
#endif
1400
45
    if (ImGui::IsGamepadKey(key))
1401
0
        BackendUsingLegacyNavInputArray = false;
1402
1403
    // Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed)
1404
45
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(ImGuiInputEventType_Key, (int)key);
1405
45
    const ImGuiKeyData* key_data = ImGui::GetKeyData(key);
1406
45
    const bool latest_key_down = latest_event ? latest_event->Key.Down : key_data->Down;
1407
45
    const float latest_key_analog = latest_event ? latest_event->Key.AnalogValue : key_data->AnalogValue;
1408
45
    if (latest_key_down == down && latest_key_analog == analog_value)
1409
1
        return;
1410
1411
    // Add event
1412
44
    ImGuiInputEvent e;
1413
44
    e.Type = ImGuiInputEventType_Key;
1414
44
    e.Source = ImGui::IsGamepadKey(key) ? ImGuiInputSource_Gamepad : ImGuiInputSource_Keyboard;
1415
44
    e.Key.Key = key;
1416
44
    e.Key.Down = down;
1417
44
    e.Key.AnalogValue = analog_value;
1418
44
    g.InputEventsQueue.push_back(e);
1419
44
}
1420
1421
void ImGuiIO::AddKeyEvent(ImGuiKey key, bool down)
1422
0
{
1423
0
    if (!AppAcceptingEvents)
1424
0
        return;
1425
0
    AddKeyAnalogEvent(key, down, down ? 1.0f : 0.0f);
1426
0
}
1427
1428
// [Optional] Call after AddKeyEvent().
1429
// Specify native keycode, scancode + Specify index for legacy <1.87 IsKeyXXX() functions with native indices.
1430
// If you are writing a backend in 2022 or don't use IsKeyXXX() with native values that are not ImGuiKey values, you can avoid calling this.
1431
void ImGuiIO::SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index)
1432
0
{
1433
0
    if (key == ImGuiKey_None)
1434
0
        return;
1435
0
    IM_ASSERT(ImGui::IsNamedKey(key)); // >= 512
1436
0
    IM_ASSERT(native_legacy_index == -1 || ImGui::IsLegacyKey((ImGuiKey)native_legacy_index)); // >= 0 && <= 511
1437
0
    IM_UNUSED(native_keycode);  // Yet unused
1438
0
    IM_UNUSED(native_scancode); // Yet unused
1439
1440
    // Build native->imgui map so old user code can still call key functions with native 0..511 values.
1441
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1442
    const int legacy_key = (native_legacy_index != -1) ? native_legacy_index : native_keycode;
1443
    if (!ImGui::IsLegacyKey((ImGuiKey)legacy_key))
1444
        return;
1445
    KeyMap[legacy_key] = key;
1446
    KeyMap[key] = legacy_key;
1447
#else
1448
0
    IM_UNUSED(key);
1449
0
    IM_UNUSED(native_legacy_index);
1450
0
#endif
1451
0
}
1452
1453
// Set master flag for accepting key/mouse/text events (default to true). Useful if you have native dialog boxes that are interrupting your application loop/refresh, and you want to disable events being queued while your app is frozen.
1454
void ImGuiIO::SetAppAcceptingEvents(bool accepting_events)
1455
0
{
1456
0
    AppAcceptingEvents = accepting_events;
1457
0
}
1458
1459
// Queue a mouse move event
1460
void ImGuiIO::AddMousePosEvent(float x, float y)
1461
352
{
1462
352
    ImGuiContext& g = *GImGui;
1463
352
    IM_ASSERT(&g.IO == this && "Can only add events to current context.");
1464
352
    if (!AppAcceptingEvents)
1465
0
        return;
1466
1467
    // Apply same flooring as UpdateMouseInputs()
1468
352
    ImVec2 pos((x > -FLT_MAX) ? ImFloorSigned(x) : x, (y > -FLT_MAX) ? ImFloorSigned(y) : y);
1469
1470
    // Filter duplicate
1471
352
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(ImGuiInputEventType_MousePos);
1472
352
    const ImVec2 latest_pos = latest_event ? ImVec2(latest_event->MousePos.PosX, latest_event->MousePos.PosY) : g.IO.MousePos;
1473
352
    if (latest_pos.x == pos.x && latest_pos.y == pos.y)
1474
137
        return;
1475
1476
215
    ImGuiInputEvent e;
1477
215
    e.Type = ImGuiInputEventType_MousePos;
1478
215
    e.Source = ImGuiInputSource_Mouse;
1479
215
    e.MousePos.PosX = pos.x;
1480
215
    e.MousePos.PosY = pos.y;
1481
215
    g.InputEventsQueue.push_back(e);
1482
215
}
1483
1484
void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down)
1485
970
{
1486
970
    ImGuiContext& g = *GImGui;
1487
970
    IM_ASSERT(&g.IO == this && "Can only add events to current context.");
1488
970
    IM_ASSERT(mouse_button >= 0 && mouse_button < ImGuiMouseButton_COUNT);
1489
970
    if (!AppAcceptingEvents)
1490
0
        return;
1491
1492
    // Filter duplicate
1493
970
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(ImGuiInputEventType_MouseButton, (int)mouse_button);
1494
970
    const bool latest_button_down = latest_event ? latest_event->MouseButton.Down : g.IO.MouseDown[mouse_button];
1495
970
    if (latest_button_down == down)
1496
236
        return;
1497
1498
734
    ImGuiInputEvent e;
1499
734
    e.Type = ImGuiInputEventType_MouseButton;
1500
734
    e.Source = ImGuiInputSource_Mouse;
1501
734
    e.MouseButton.Button = mouse_button;
1502
734
    e.MouseButton.Down = down;
1503
734
    g.InputEventsQueue.push_back(e);
1504
734
}
1505
1506
// Queue a mouse wheel event (some mouse/API may only have a Y component)
1507
void ImGuiIO::AddMouseWheelEvent(float wheel_x, float wheel_y)
1508
247
{
1509
247
    ImGuiContext& g = *GImGui;
1510
247
    IM_ASSERT(&g.IO == this && "Can only add events to current context.");
1511
1512
    // Filter duplicate (unlike most events, wheel values are relative and easy to filter)
1513
247
    if (!AppAcceptingEvents || (wheel_x == 0.0f && wheel_y == 0.0f))
1514
2
        return;
1515
1516
245
    ImGuiInputEvent e;
1517
245
    e.Type = ImGuiInputEventType_MouseWheel;
1518
245
    e.Source = ImGuiInputSource_Mouse;
1519
245
    e.MouseWheel.WheelX = wheel_x;
1520
245
    e.MouseWheel.WheelY = wheel_y;
1521
245
    g.InputEventsQueue.push_back(e);
1522
245
}
1523
1524
void ImGuiIO::AddMouseViewportEvent(ImGuiID viewport_id)
1525
0
{
1526
0
    ImGuiContext& g = *GImGui;
1527
0
    IM_ASSERT(&g.IO == this && "Can only add events to current context.");
1528
0
    IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport);
1529
0
    if (!AppAcceptingEvents)
1530
0
        return;
1531
1532
    // Filter duplicate
1533
0
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(ImGuiInputEventType_MouseViewport);
1534
0
    const ImGuiID latest_viewport_id = latest_event ? latest_event->MouseViewport.HoveredViewportID : g.IO.MouseHoveredViewport;
1535
0
    if (latest_viewport_id == viewport_id)
1536
0
        return;
1537
1538
0
    ImGuiInputEvent e;
1539
0
    e.Type = ImGuiInputEventType_MouseViewport;
1540
0
    e.Source = ImGuiInputSource_Mouse;
1541
0
    e.MouseViewport.HoveredViewportID = viewport_id;
1542
0
    g.InputEventsQueue.push_back(e);
1543
0
}
1544
1545
void ImGuiIO::AddFocusEvent(bool focused)
1546
115
{
1547
115
    ImGuiContext& g = *GImGui;
1548
115
    IM_ASSERT(&g.IO == this && "Can only add events to current context.");
1549
1550
    // Filter duplicate
1551
115
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(ImGuiInputEventType_Focus);
1552
115
    const bool latest_focused = latest_event ? latest_event->AppFocused.Focused : !g.IO.AppFocusLost;
1553
115
    if (latest_focused == focused)
1554
16
        return;
1555
1556
99
    ImGuiInputEvent e;
1557
99
    e.Type = ImGuiInputEventType_Focus;
1558
99
    e.AppFocused.Focused = focused;
1559
99
    g.InputEventsQueue.push_back(e);
1560
99
}
1561
1562
//-----------------------------------------------------------------------------
1563
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
1564
//-----------------------------------------------------------------------------
1565
1566
ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
1567
0
{
1568
0
    IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau()
1569
0
    ImVec2 p_last = p1;
1570
0
    ImVec2 p_closest;
1571
0
    float p_closest_dist2 = FLT_MAX;
1572
0
    float t_step = 1.0f / (float)num_segments;
1573
0
    for (int i_step = 1; i_step <= num_segments; i_step++)
1574
0
    {
1575
0
        ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step);
1576
0
        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1577
0
        float dist2 = ImLengthSqr(p - p_line);
1578
0
        if (dist2 < p_closest_dist2)
1579
0
        {
1580
0
            p_closest = p_line;
1581
0
            p_closest_dist2 = dist2;
1582
0
        }
1583
0
        p_last = p_current;
1584
0
    }
1585
0
    return p_closest;
1586
0
}
1587
1588
// Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
1589
static void ImBezierCubicClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, ImVec2& p_last, float& p_closest_dist2, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level)
1590
0
{
1591
0
    float dx = x4 - x1;
1592
0
    float dy = y4 - y1;
1593
0
    float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
1594
0
    float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
1595
0
    d2 = (d2 >= 0) ? d2 : -d2;
1596
0
    d3 = (d3 >= 0) ? d3 : -d3;
1597
0
    if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
1598
0
    {
1599
0
        ImVec2 p_current(x4, y4);
1600
0
        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1601
0
        float dist2 = ImLengthSqr(p - p_line);
1602
0
        if (dist2 < p_closest_dist2)
1603
0
        {
1604
0
            p_closest = p_line;
1605
0
            p_closest_dist2 = dist2;
1606
0
        }
1607
0
        p_last = p_current;
1608
0
    }
1609
0
    else if (level < 10)
1610
0
    {
1611
0
        float x12 = (x1 + x2)*0.5f,       y12 = (y1 + y2)*0.5f;
1612
0
        float x23 = (x2 + x3)*0.5f,       y23 = (y2 + y3)*0.5f;
1613
0
        float x34 = (x3 + x4)*0.5f,       y34 = (y3 + y4)*0.5f;
1614
0
        float x123 = (x12 + x23)*0.5f,    y123 = (y12 + y23)*0.5f;
1615
0
        float x234 = (x23 + x34)*0.5f,    y234 = (y23 + y34)*0.5f;
1616
0
        float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f;
1617
0
        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
1618
0
        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
1619
0
    }
1620
0
}
1621
1622
// tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
1623
// Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
1624
ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
1625
0
{
1626
0
    IM_ASSERT(tess_tol > 0.0f);
1627
0
    ImVec2 p_last = p1;
1628
0
    ImVec2 p_closest;
1629
0
    float p_closest_dist2 = FLT_MAX;
1630
0
    ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, tess_tol, 0);
1631
0
    return p_closest;
1632
0
}
1633
1634
ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
1635
0
{
1636
0
    ImVec2 ap = p - a;
1637
0
    ImVec2 ab_dir = b - a;
1638
0
    float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
1639
0
    if (dot < 0.0f)
1640
0
        return a;
1641
0
    float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
1642
0
    if (dot > ab_len_sqr)
1643
0
        return b;
1644
0
    return a + ab_dir * dot / ab_len_sqr;
1645
0
}
1646
1647
bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1648
0
{
1649
0
    bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
1650
0
    bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
1651
0
    bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
1652
0
    return ((b1 == b2) && (b2 == b3));
1653
0
}
1654
1655
void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
1656
0
{
1657
0
    ImVec2 v0 = b - a;
1658
0
    ImVec2 v1 = c - a;
1659
0
    ImVec2 v2 = p - a;
1660
0
    const float denom = v0.x * v1.y - v1.x * v0.y;
1661
0
    out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
1662
0
    out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
1663
0
    out_u = 1.0f - out_v - out_w;
1664
0
}
1665
1666
ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1667
0
{
1668
0
    ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
1669
0
    ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
1670
0
    ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
1671
0
    float dist2_ab = ImLengthSqr(p - proj_ab);
1672
0
    float dist2_bc = ImLengthSqr(p - proj_bc);
1673
0
    float dist2_ca = ImLengthSqr(p - proj_ca);
1674
0
    float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
1675
0
    if (m == dist2_ab)
1676
0
        return proj_ab;
1677
0
    if (m == dist2_bc)
1678
0
        return proj_bc;
1679
0
    return proj_ca;
1680
0
}
1681
1682
//-----------------------------------------------------------------------------
1683
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
1684
//-----------------------------------------------------------------------------
1685
1686
// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
1687
int ImStricmp(const char* str1, const char* str2)
1688
0
{
1689
0
    int d;
1690
0
    while ((d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; }
1691
0
    return d;
1692
0
}
1693
1694
int ImStrnicmp(const char* str1, const char* str2, size_t count)
1695
0
{
1696
0
    int d = 0;
1697
0
    while (count > 0 && (d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
1698
0
    return d;
1699
0
}
1700
1701
void ImStrncpy(char* dst, const char* src, size_t count)
1702
0
{
1703
0
    if (count < 1)
1704
0
        return;
1705
0
    if (count > 1)
1706
0
        strncpy(dst, src, count - 1);
1707
0
    dst[count - 1] = 0;
1708
0
}
1709
1710
char* ImStrdup(const char* str)
1711
3
{
1712
3
    size_t len = strlen(str);
1713
3
    void* buf = IM_ALLOC(len + 1);
1714
3
    return (char*)memcpy(buf, (const void*)str, len + 1);
1715
3
}
1716
1717
char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
1718
0
{
1719
0
    size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;
1720
0
    size_t src_size = strlen(src) + 1;
1721
0
    if (dst_buf_size < src_size)
1722
0
    {
1723
0
        IM_FREE(dst);
1724
0
        dst = (char*)IM_ALLOC(src_size);
1725
0
        if (p_dst_size)
1726
0
            *p_dst_size = src_size;
1727
0
    }
1728
0
    return (char*)memcpy(dst, (const void*)src, src_size);
1729
0
}
1730
1731
const char* ImStrchrRange(const char* str, const char* str_end, char c)
1732
0
{
1733
0
    const char* p = (const char*)memchr(str, (int)c, str_end - str);
1734
0
    return p;
1735
0
}
1736
1737
int ImStrlenW(const ImWchar* str)
1738
0
{
1739
    //return (int)wcslen((const wchar_t*)str);  // FIXME-OPT: Could use this when wchar_t are 16-bit
1740
0
    int n = 0;
1741
0
    while (*str++) n++;
1742
0
    return n;
1743
0
}
1744
1745
// Find end-of-line. Return pointer will point to either first \n, either str_end.
1746
const char* ImStreolRange(const char* str, const char* str_end)
1747
0
{
1748
0
    const char* p = (const char*)memchr(str, '\n', str_end - str);
1749
0
    return p ? p : str_end;
1750
0
}
1751
1752
const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
1753
0
{
1754
0
    while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
1755
0
        buf_mid_line--;
1756
0
    return buf_mid_line;
1757
0
}
1758
1759
const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
1760
0
{
1761
0
    if (!needle_end)
1762
0
        needle_end = needle + strlen(needle);
1763
1764
0
    const char un0 = (char)ImToUpper(*needle);
1765
0
    while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
1766
0
    {
1767
0
        if (ImToUpper(*haystack) == un0)
1768
0
        {
1769
0
            const char* b = needle + 1;
1770
0
            for (const char* a = haystack + 1; b < needle_end; a++, b++)
1771
0
                if (ImToUpper(*a) != ImToUpper(*b))
1772
0
                    break;
1773
0
            if (b == needle_end)
1774
0
                return haystack;
1775
0
        }
1776
0
        haystack++;
1777
0
    }
1778
0
    return NULL;
1779
0
}
1780
1781
// Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible.
1782
void ImStrTrimBlanks(char* buf)
1783
0
{
1784
0
    char* p = buf;
1785
0
    while (p[0] == ' ' || p[0] == '\t')     // Leading blanks
1786
0
        p++;
1787
0
    char* p_start = p;
1788
0
    while (*p != 0)                         // Find end of string
1789
0
        p++;
1790
0
    while (p > p_start && (p[-1] == ' ' || p[-1] == '\t'))  // Trailing blanks
1791
0
        p--;
1792
0
    if (p_start != buf)                     // Copy memory if we had leading blanks
1793
0
        memmove(buf, p_start, p - p_start);
1794
0
    buf[p - p_start] = 0;                   // Zero terminate
1795
0
}
1796
1797
const char* ImStrSkipBlank(const char* str)
1798
0
{
1799
0
    while (str[0] == ' ' || str[0] == '\t')
1800
0
        str++;
1801
0
    return str;
1802
0
}
1803
1804
// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
1805
// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm.
1806
// B) When buf==NULL vsnprintf() will return the output size.
1807
#ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1808
1809
// We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
1810
// You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1811
// and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
1812
// designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
1813
#ifdef IMGUI_USE_STB_SPRINTF
1814
#define STB_SPRINTF_IMPLEMENTATION
1815
#ifdef IMGUI_STB_SPRINTF_FILENAME
1816
#include IMGUI_STB_SPRINTF_FILENAME
1817
#else
1818
#include "stb_sprintf.h"
1819
#endif
1820
#endif
1821
1822
#if defined(_MSC_VER) && !defined(vsnprintf)
1823
#define vsnprintf _vsnprintf
1824
#endif
1825
1826
int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
1827
1
{
1828
1
    va_list args;
1829
1
    va_start(args, fmt);
1830
#ifdef IMGUI_USE_STB_SPRINTF
1831
    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1832
#else
1833
1
    int w = vsnprintf(buf, buf_size, fmt, args);
1834
1
#endif
1835
1
    va_end(args);
1836
1
    if (buf == NULL)
1837
0
        return w;
1838
1
    if (w == -1 || w >= (int)buf_size)
1839
0
        w = (int)buf_size - 1;
1840
1
    buf[w] = 0;
1841
1
    return w;
1842
1
}
1843
1844
int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
1845
3.00k
{
1846
#ifdef IMGUI_USE_STB_SPRINTF
1847
    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1848
#else
1849
3.00k
    int w = vsnprintf(buf, buf_size, fmt, args);
1850
3.00k
#endif
1851
3.00k
    if (buf == NULL)
1852
0
        return w;
1853
3.00k
    if (w == -1 || w >= (int)buf_size)
1854
0
        w = (int)buf_size - 1;
1855
3.00k
    buf[w] = 0;
1856
3.00k
    return w;
1857
3.00k
}
1858
#endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1859
1860
void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, const char* fmt, ...)
1861
3.00k
{
1862
3.00k
    ImGuiContext& g = *GImGui;
1863
3.00k
    va_list args;
1864
3.00k
    va_start(args, fmt);
1865
3.00k
    if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)
1866
0
    {
1867
0
        const char* buf = va_arg(args, const char*); // Skip formatting when using "%s"
1868
0
        *out_buf = buf;
1869
0
        if (out_buf_end) { *out_buf_end = buf + strlen(buf); }
1870
0
    }
1871
3.00k
    else
1872
3.00k
    {
1873
3.00k
        int buf_len = ImFormatStringV(g.TempBuffer.Data, g.TempBuffer.Size, fmt, args);
1874
3.00k
        *out_buf = g.TempBuffer.Data;
1875
3.00k
        if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
1876
3.00k
    }
1877
3.00k
    va_end(args);
1878
3.00k
}
1879
1880
void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, const char* fmt, va_list args)
1881
0
{
1882
0
    ImGuiContext& g = *GImGui;
1883
0
    if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)
1884
0
    {
1885
0
        const char* buf = va_arg(args, const char*); // Skip formatting when using "%s"
1886
0
        *out_buf = buf;
1887
0
        if (out_buf_end) { *out_buf_end = buf + strlen(buf); }
1888
0
    }
1889
0
    else
1890
0
    {
1891
0
        int buf_len = ImFormatStringV(g.TempBuffer.Data, g.TempBuffer.Size, fmt, args);
1892
0
        *out_buf = g.TempBuffer.Data;
1893
0
        if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
1894
0
    }
1895
0
}
1896
1897
// CRC32 needs a 1KB lookup table (not cache friendly)
1898
// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
1899
// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
1900
static const ImU32 GCrc32LookupTable[256] =
1901
{
1902
    0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
1903
    0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
1904
    0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
1905
    0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
1906
    0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
1907
    0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
1908
    0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
1909
    0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
1910
    0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
1911
    0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
1912
    0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
1913
    0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
1914
    0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
1915
    0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
1916
    0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
1917
    0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
1918
};
1919
1920
// Known size hash
1921
// It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
1922
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
1923
ImGuiID ImHashData(const void* data_p, size_t data_size, ImU32 seed)
1924
3.00k
{
1925
3.00k
    ImU32 crc = ~seed;
1926
3.00k
    const unsigned char* data = (const unsigned char*)data_p;
1927
3.00k
    const ImU32* crc32_lut = GCrc32LookupTable;
1928
15.0k
    while (data_size-- != 0)
1929
12.0k
        crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
1930
3.00k
    return ~crc;
1931
3.00k
}
1932
1933
// Zero-terminated string hash, with support for ### to reset back to seed value
1934
// We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
1935
// Because this syntax is rarely used we are optimizing for the common case.
1936
// - If we reach ### in the string we discard the hash so far and reset to the seed.
1937
// - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
1938
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
1939
ImGuiID ImHashStr(const char* data_p, size_t data_size, ImU32 seed)
1940
27.1k
{
1941
27.1k
    seed = ~seed;
1942
27.1k
    ImU32 crc = seed;
1943
27.1k
    const unsigned char* data = (const unsigned char*)data_p;
1944
27.1k
    const ImU32* crc32_lut = GCrc32LookupTable;
1945
27.1k
    if (data_size != 0)
1946
0
    {
1947
0
        while (data_size-- != 0)
1948
0
        {
1949
0
            unsigned char c = *data++;
1950
0
            if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
1951
0
                crc = seed;
1952
0
            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
1953
0
        }
1954
0
    }
1955
27.1k
    else
1956
27.1k
    {
1957
355k
        while (unsigned char c = *data++)
1958
328k
        {
1959
328k
            if (c == '#' && data[0] == '#' && data[1] == '#')
1960
0
                crc = seed;
1961
328k
            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
1962
328k
        }
1963
27.1k
    }
1964
27.1k
    return ~crc;
1965
27.1k
}
1966
1967
//-----------------------------------------------------------------------------
1968
// [SECTION] MISC HELPERS/UTILITIES (File functions)
1969
//-----------------------------------------------------------------------------
1970
1971
// Default file functions
1972
#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
1973
1974
ImFileHandle ImFileOpen(const char* filename, const char* mode)
1975
0
{
1976
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)
1977
    // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
1978
    // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
1979
    const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
1980
    const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
1981
    ImVector<wchar_t> buf;
1982
    buf.resize(filename_wsize + mode_wsize);
1983
    ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, (wchar_t*)&buf[0], filename_wsize);
1984
    ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, (wchar_t*)&buf[filename_wsize], mode_wsize);
1985
    return ::_wfopen((const wchar_t*)&buf[0], (const wchar_t*)&buf[filename_wsize]);
1986
#else
1987
0
    return fopen(filename, mode);
1988
0
#endif
1989
0
}
1990
1991
// We should in theory be using fseeko()/ftello() with off_t and _fseeki64()/_ftelli64() with __int64, waiting for the PR that does that in a very portable pre-C++11 zero-warnings way.
1992
0
bool    ImFileClose(ImFileHandle f)     { return fclose(f) == 0; }
1993
0
ImU64   ImFileGetSize(ImFileHandle f)   { long off = 0, sz = 0; return ((off = ftell(f)) != -1 && !fseek(f, 0, SEEK_END) && (sz = ftell(f)) != -1 && !fseek(f, off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; }
1994
0
ImU64   ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f)           { return fread(data, (size_t)sz, (size_t)count, f); }
1995
0
ImU64   ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f)    { return fwrite(data, (size_t)sz, (size_t)count, f); }
1996
#endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
1997
1998
// Helper: Load file content into memory
1999
// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
2000
// This can't really be used with "rt" because fseek size won't match read size.
2001
void*   ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
2002
0
{
2003
0
    IM_ASSERT(filename && mode);
2004
0
    if (out_file_size)
2005
0
        *out_file_size = 0;
2006
2007
0
    ImFileHandle f;
2008
0
    if ((f = ImFileOpen(filename, mode)) == NULL)
2009
0
        return NULL;
2010
2011
0
    size_t file_size = (size_t)ImFileGetSize(f);
2012
0
    if (file_size == (size_t)-1)
2013
0
    {
2014
0
        ImFileClose(f);
2015
0
        return NULL;
2016
0
    }
2017
2018
0
    void* file_data = IM_ALLOC(file_size + padding_bytes);
2019
0
    if (file_data == NULL)
2020
0
    {
2021
0
        ImFileClose(f);
2022
0
        return NULL;
2023
0
    }
2024
0
    if (ImFileRead(file_data, 1, file_size, f) != file_size)
2025
0
    {
2026
0
        ImFileClose(f);
2027
0
        IM_FREE(file_data);
2028
0
        return NULL;
2029
0
    }
2030
0
    if (padding_bytes > 0)
2031
0
        memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
2032
2033
0
    ImFileClose(f);
2034
0
    if (out_file_size)
2035
0
        *out_file_size = file_size;
2036
2037
0
    return file_data;
2038
0
}
2039
2040
//-----------------------------------------------------------------------------
2041
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
2042
//-----------------------------------------------------------------------------
2043
2044
IM_MSVC_RUNTIME_CHECKS_OFF
2045
2046
// Convert UTF-8 to 32-bit character, process single character input.
2047
// A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8).
2048
// We handle UTF-8 decoding error by skipping forward.
2049
int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
2050
2.47M
{
2051
2.47M
    static const char lengths[32] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0 };
2052
2.47M
    static const int masks[]  = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 };
2053
2.47M
    static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 };
2054
2.47M
    static const int shiftc[] = { 0, 18, 12, 6, 0 };
2055
2.47M
    static const int shifte[] = { 0, 6, 4, 2, 0 };
2056
2.47M
    int len = lengths[*(const unsigned char*)in_text >> 3];
2057
2.47M
    int wanted = len + (len ? 0 : 1);
2058
2059
2.47M
    if (in_text_end == NULL)
2060
0
        in_text_end = in_text + wanted; // Max length, nulls will be taken into account.
2061
2062
    // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here,
2063
    // so it is fast even with excessive branching.
2064
2.47M
    unsigned char s[4];
2065
2.47M
    s[0] = in_text + 0 < in_text_end ? in_text[0] : 0;
2066
2.47M
    s[1] = in_text + 1 < in_text_end ? in_text[1] : 0;
2067
2.47M
    s[2] = in_text + 2 < in_text_end ? in_text[2] : 0;
2068
2.47M
    s[3] = in_text + 3 < in_text_end ? in_text[3] : 0;
2069
2070
    // Assume a four-byte character and load four bytes. Unused bits are shifted out.
2071
2.47M
    *out_char  = (uint32_t)(s[0] & masks[len]) << 18;
2072
2.47M
    *out_char |= (uint32_t)(s[1] & 0x3f) << 12;
2073
2.47M
    *out_char |= (uint32_t)(s[2] & 0x3f) <<  6;
2074
2.47M
    *out_char |= (uint32_t)(s[3] & 0x3f) <<  0;
2075
2.47M
    *out_char >>= shiftc[len];
2076
2077
    // Accumulate the various error conditions.
2078
2.47M
    int e = 0;
2079
2.47M
    e  = (*out_char < mins[len]) << 6; // non-canonical encoding
2080
2.47M
    e |= ((*out_char >> 11) == 0x1b) << 7;  // surrogate half?
2081
2.47M
    e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8;  // out of range?
2082
2.47M
    e |= (s[1] & 0xc0) >> 2;
2083
2.47M
    e |= (s[2] & 0xc0) >> 4;
2084
2.47M
    e |= (s[3]       ) >> 6;
2085
2.47M
    e ^= 0x2a; // top two bits of each tail byte correct?
2086
2.47M
    e >>= shifte[len];
2087
2088
2.47M
    if (e)
2089
3.21k
    {
2090
        // No bytes are consumed when *in_text == 0 || in_text == in_text_end.
2091
        // One byte is consumed in case of invalid first byte of in_text.
2092
        // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes.
2093
        // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s.
2094
3.21k
        wanted = ImMin(wanted, !!s[0] + !!s[1] + !!s[2] + !!s[3]);
2095
3.21k
        *out_char = IM_UNICODE_CODEPOINT_INVALID;
2096
3.21k
    }
2097
2098
2.47M
    return wanted;
2099
2.47M
}
2100
2101
int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
2102
0
{
2103
0
    ImWchar* buf_out = buf;
2104
0
    ImWchar* buf_end = buf + buf_size;
2105
0
    while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2106
0
    {
2107
0
        unsigned int c;
2108
0
        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2109
0
        *buf_out++ = (ImWchar)c;
2110
0
    }
2111
0
    *buf_out = 0;
2112
0
    if (in_text_remaining)
2113
0
        *in_text_remaining = in_text;
2114
0
    return (int)(buf_out - buf);
2115
0
}
2116
2117
int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
2118
0
{
2119
0
    int char_count = 0;
2120
0
    while ((!in_text_end || in_text < in_text_end) && *in_text)
2121
0
    {
2122
0
        unsigned int c;
2123
0
        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2124
0
        char_count++;
2125
0
    }
2126
0
    return char_count;
2127
0
}
2128
2129
// Based on stb_to_utf8() from github.com/nothings/stb/
2130
static inline int ImTextCharToUtf8_inline(char* buf, int buf_size, unsigned int c)
2131
0
{
2132
0
    if (c < 0x80)
2133
0
    {
2134
0
        buf[0] = (char)c;
2135
0
        return 1;
2136
0
    }
2137
0
    if (c < 0x800)
2138
0
    {
2139
0
        if (buf_size < 2) return 0;
2140
0
        buf[0] = (char)(0xc0 + (c >> 6));
2141
0
        buf[1] = (char)(0x80 + (c & 0x3f));
2142
0
        return 2;
2143
0
    }
2144
0
    if (c < 0x10000)
2145
0
    {
2146
0
        if (buf_size < 3) return 0;
2147
0
        buf[0] = (char)(0xe0 + (c >> 12));
2148
0
        buf[1] = (char)(0x80 + ((c >> 6) & 0x3f));
2149
0
        buf[2] = (char)(0x80 + ((c ) & 0x3f));
2150
0
        return 3;
2151
0
    }
2152
0
    if (c <= 0x10FFFF)
2153
0
    {
2154
0
        if (buf_size < 4) return 0;
2155
0
        buf[0] = (char)(0xf0 + (c >> 18));
2156
0
        buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
2157
0
        buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
2158
0
        buf[3] = (char)(0x80 + ((c ) & 0x3f));
2159
0
        return 4;
2160
0
    }
2161
    // Invalid code point, the max unicode is 0x10FFFF
2162
0
    return 0;
2163
0
}
2164
2165
const char* ImTextCharToUtf8(char out_buf[5], unsigned int c)
2166
0
{
2167
0
    int count = ImTextCharToUtf8_inline(out_buf, 5, c);
2168
0
    out_buf[count] = 0;
2169
0
    return out_buf;
2170
0
}
2171
2172
// Not optimal but we very rarely use this function.
2173
int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
2174
0
{
2175
0
    unsigned int unused = 0;
2176
0
    return ImTextCharFromUtf8(&unused, in_text, in_text_end);
2177
0
}
2178
2179
static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
2180
0
{
2181
0
    if (c < 0x80) return 1;
2182
0
    if (c < 0x800) return 2;
2183
0
    if (c < 0x10000) return 3;
2184
0
    if (c <= 0x10FFFF) return 4;
2185
0
    return 3;
2186
0
}
2187
2188
int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
2189
0
{
2190
0
    char* buf_p = out_buf;
2191
0
    const char* buf_end = out_buf + out_buf_size;
2192
0
    while (buf_p < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2193
0
    {
2194
0
        unsigned int c = (unsigned int)(*in_text++);
2195
0
        if (c < 0x80)
2196
0
            *buf_p++ = (char)c;
2197
0
        else
2198
0
            buf_p += ImTextCharToUtf8_inline(buf_p, (int)(buf_end - buf_p - 1), c);
2199
0
    }
2200
0
    *buf_p = 0;
2201
0
    return (int)(buf_p - out_buf);
2202
0
}
2203
2204
int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
2205
0
{
2206
0
    int bytes_count = 0;
2207
0
    while ((!in_text_end || in_text < in_text_end) && *in_text)
2208
0
    {
2209
0
        unsigned int c = (unsigned int)(*in_text++);
2210
0
        if (c < 0x80)
2211
0
            bytes_count++;
2212
0
        else
2213
0
            bytes_count += ImTextCountUtf8BytesFromChar(c);
2214
0
    }
2215
0
    return bytes_count;
2216
0
}
2217
IM_MSVC_RUNTIME_CHECKS_RESTORE
2218
2219
//-----------------------------------------------------------------------------
2220
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
2221
// Note: The Convert functions are early design which are not consistent with other API.
2222
//-----------------------------------------------------------------------------
2223
2224
IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)
2225
0
{
2226
0
    float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
2227
0
    int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
2228
0
    int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
2229
0
    int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
2230
0
    return IM_COL32(r, g, b, 0xFF);
2231
0
}
2232
2233
ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
2234
13.8k
{
2235
13.8k
    float s = 1.0f / 255.0f;
2236
13.8k
    return ImVec4(
2237
13.8k
        ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
2238
13.8k
        ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
2239
13.8k
        ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
2240
13.8k
        ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
2241
13.8k
}
2242
2243
ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
2244
62.2k
{
2245
62.2k
    ImU32 out;
2246
62.2k
    out  = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
2247
62.2k
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
2248
62.2k
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
2249
62.2k
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
2250
62.2k
    return out;
2251
62.2k
}
2252
2253
// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
2254
// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
2255
void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
2256
0
{
2257
0
    float K = 0.f;
2258
0
    if (g < b)
2259
0
    {
2260
0
        ImSwap(g, b);
2261
0
        K = -1.f;
2262
0
    }
2263
0
    if (r < g)
2264
0
    {
2265
0
        ImSwap(r, g);
2266
0
        K = -2.f / 6.f - K;
2267
0
    }
2268
2269
0
    const float chroma = r - (g < b ? g : b);
2270
0
    out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
2271
0
    out_s = chroma / (r + 1e-20f);
2272
0
    out_v = r;
2273
0
}
2274
2275
// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
2276
// also http://en.wikipedia.org/wiki/HSL_and_HSV
2277
void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
2278
0
{
2279
0
    if (s == 0.0f)
2280
0
    {
2281
        // gray
2282
0
        out_r = out_g = out_b = v;
2283
0
        return;
2284
0
    }
2285
2286
0
    h = ImFmod(h, 1.0f) / (60.0f / 360.0f);
2287
0
    int   i = (int)h;
2288
0
    float f = h - (float)i;
2289
0
    float p = v * (1.0f - s);
2290
0
    float q = v * (1.0f - s * f);
2291
0
    float t = v * (1.0f - s * (1.0f - f));
2292
2293
0
    switch (i)
2294
0
    {
2295
0
    case 0: out_r = v; out_g = t; out_b = p; break;
2296
0
    case 1: out_r = q; out_g = v; out_b = p; break;
2297
0
    case 2: out_r = p; out_g = v; out_b = t; break;
2298
0
    case 3: out_r = p; out_g = q; out_b = v; break;
2299
0
    case 4: out_r = t; out_g = p; out_b = v; break;
2300
0
    case 5: default: out_r = v; out_g = p; out_b = q; break;
2301
0
    }
2302
0
}
2303
2304
//-----------------------------------------------------------------------------
2305
// [SECTION] ImGuiStorage
2306
// Helper: Key->value storage
2307
//-----------------------------------------------------------------------------
2308
2309
// std::lower_bound but without the bullshit
2310
static ImGuiStorage::ImGuiStoragePair* LowerBound(ImVector<ImGuiStorage::ImGuiStoragePair>& data, ImGuiID key)
2311
9.00k
{
2312
9.00k
    ImGuiStorage::ImGuiStoragePair* first = data.Data;
2313
9.00k
    ImGuiStorage::ImGuiStoragePair* last = data.Data + data.Size;
2314
9.00k
    size_t count = (size_t)(last - first);
2315
27.0k
    while (count > 0)
2316
18.0k
    {
2317
18.0k
        size_t count2 = count >> 1;
2318
18.0k
        ImGuiStorage::ImGuiStoragePair* mid = first + count2;
2319
18.0k
        if (mid->key < key)
2320
6.00k
        {
2321
6.00k
            first = ++mid;
2322
6.00k
            count -= count2 + 1;
2323
6.00k
        }
2324
12.0k
        else
2325
12.0k
        {
2326
12.0k
            count = count2;
2327
12.0k
        }
2328
18.0k
    }
2329
9.00k
    return first;
2330
9.00k
}
2331
2332
// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
2333
void ImGuiStorage::BuildSortByKey()
2334
0
{
2335
0
    struct StaticFunc
2336
0
    {
2337
0
        static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs)
2338
0
        {
2339
            // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
2340
0
            if (((const ImGuiStoragePair*)lhs)->key > ((const ImGuiStoragePair*)rhs)->key) return +1;
2341
0
            if (((const ImGuiStoragePair*)lhs)->key < ((const ImGuiStoragePair*)rhs)->key) return -1;
2342
0
            return 0;
2343
0
        }
2344
0
    };
2345
0
    ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), StaticFunc::PairComparerByID);
2346
0
}
2347
2348
int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
2349
0
{
2350
0
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2351
0
    if (it == Data.end() || it->key != key)
2352
0
        return default_val;
2353
0
    return it->val_i;
2354
0
}
2355
2356
bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
2357
0
{
2358
0
    return GetInt(key, default_val ? 1 : 0) != 0;
2359
0
}
2360
2361
float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
2362
0
{
2363
0
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2364
0
    if (it == Data.end() || it->key != key)
2365
0
        return default_val;
2366
0
    return it->val_f;
2367
0
}
2368
2369
void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
2370
9.00k
{
2371
9.00k
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2372
9.00k
    if (it == Data.end() || it->key != key)
2373
3
        return NULL;
2374
9.00k
    return it->val_p;
2375
9.00k
}
2376
2377
// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.
2378
int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
2379
0
{
2380
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2381
0
    if (it == Data.end() || it->key != key)
2382
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2383
0
    return &it->val_i;
2384
0
}
2385
2386
bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
2387
0
{
2388
0
    return (bool*)GetIntRef(key, default_val ? 1 : 0);
2389
0
}
2390
2391
float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
2392
0
{
2393
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2394
0
    if (it == Data.end() || it->key != key)
2395
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2396
0
    return &it->val_f;
2397
0
}
2398
2399
void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
2400
0
{
2401
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2402
0
    if (it == Data.end() || it->key != key)
2403
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2404
0
    return &it->val_p;
2405
0
}
2406
2407
// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame)
2408
void ImGuiStorage::SetInt(ImGuiID key, int val)
2409
0
{
2410
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2411
0
    if (it == Data.end() || it->key != key)
2412
0
    {
2413
0
        Data.insert(it, ImGuiStoragePair(key, val));
2414
0
        return;
2415
0
    }
2416
0
    it->val_i = val;
2417
0
}
2418
2419
void ImGuiStorage::SetBool(ImGuiID key, bool val)
2420
0
{
2421
0
    SetInt(key, val ? 1 : 0);
2422
0
}
2423
2424
void ImGuiStorage::SetFloat(ImGuiID key, float val)
2425
0
{
2426
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2427
0
    if (it == Data.end() || it->key != key)
2428
0
    {
2429
0
        Data.insert(it, ImGuiStoragePair(key, val));
2430
0
        return;
2431
0
    }
2432
0
    it->val_f = val;
2433
0
}
2434
2435
void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
2436
3
{
2437
3
    ImGuiStoragePair* it = LowerBound(Data, key);
2438
3
    if (it == Data.end() || it->key != key)
2439
3
    {
2440
3
        Data.insert(it, ImGuiStoragePair(key, val));
2441
3
        return;
2442
3
    }
2443
0
    it->val_p = val;
2444
0
}
2445
2446
void ImGuiStorage::SetAllInt(int v)
2447
0
{
2448
0
    for (int i = 0; i < Data.Size; i++)
2449
0
        Data[i].val_i = v;
2450
0
}
2451
2452
//-----------------------------------------------------------------------------
2453
// [SECTION] ImGuiTextFilter
2454
//-----------------------------------------------------------------------------
2455
2456
// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
2457
ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077
2458
0
{
2459
0
    InputBuf[0] = 0;
2460
0
    CountGrep = 0;
2461
0
    if (default_filter)
2462
0
    {
2463
0
        ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
2464
0
        Build();
2465
0
    }
2466
0
}
2467
2468
bool ImGuiTextFilter::Draw(const char* label, float width)
2469
0
{
2470
0
    if (width != 0.0f)
2471
0
        ImGui::SetNextItemWidth(width);
2472
0
    bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
2473
0
    if (value_changed)
2474
0
        Build();
2475
0
    return value_changed;
2476
0
}
2477
2478
void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
2479
0
{
2480
0
    out->resize(0);
2481
0
    const char* wb = b;
2482
0
    const char* we = wb;
2483
0
    while (we < e)
2484
0
    {
2485
0
        if (*we == separator)
2486
0
        {
2487
0
            out->push_back(ImGuiTextRange(wb, we));
2488
0
            wb = we + 1;
2489
0
        }
2490
0
        we++;
2491
0
    }
2492
0
    if (wb != we)
2493
0
        out->push_back(ImGuiTextRange(wb, we));
2494
0
}
2495
2496
void ImGuiTextFilter::Build()
2497
0
{
2498
0
    Filters.resize(0);
2499
0
    ImGuiTextRange input_range(InputBuf, InputBuf + strlen(InputBuf));
2500
0
    input_range.split(',', &Filters);
2501
2502
0
    CountGrep = 0;
2503
0
    for (int i = 0; i != Filters.Size; i++)
2504
0
    {
2505
0
        ImGuiTextRange& f = Filters[i];
2506
0
        while (f.b < f.e && ImCharIsBlankA(f.b[0]))
2507
0
            f.b++;
2508
0
        while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
2509
0
            f.e--;
2510
0
        if (f.empty())
2511
0
            continue;
2512
0
        if (Filters[i].b[0] != '-')
2513
0
            CountGrep += 1;
2514
0
    }
2515
0
}
2516
2517
bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
2518
0
{
2519
0
    if (Filters.empty())
2520
0
        return true;
2521
2522
0
    if (text == NULL)
2523
0
        text = "";
2524
2525
0
    for (int i = 0; i != Filters.Size; i++)
2526
0
    {
2527
0
        const ImGuiTextRange& f = Filters[i];
2528
0
        if (f.empty())
2529
0
            continue;
2530
0
        if (f.b[0] == '-')
2531
0
        {
2532
            // Subtract
2533
0
            if (ImStristr(text, text_end, f.b + 1, f.e) != NULL)
2534
0
                return false;
2535
0
        }
2536
0
        else
2537
0
        {
2538
            // Grep
2539
0
            if (ImStristr(text, text_end, f.b, f.e) != NULL)
2540
0
                return true;
2541
0
        }
2542
0
    }
2543
2544
    // Implicit * grep
2545
0
    if (CountGrep == 0)
2546
0
        return true;
2547
2548
0
    return false;
2549
0
}
2550
2551
//-----------------------------------------------------------------------------
2552
// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
2553
//-----------------------------------------------------------------------------
2554
2555
// On some platform vsnprintf() takes va_list by reference and modifies it.
2556
// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
2557
#ifndef va_copy
2558
#if defined(__GNUC__) || defined(__clang__)
2559
#define va_copy(dest, src) __builtin_va_copy(dest, src)
2560
#else
2561
#define va_copy(dest, src) (dest = src)
2562
#endif
2563
#endif
2564
2565
char ImGuiTextBuffer::EmptyString[1] = { 0 };
2566
2567
void ImGuiTextBuffer::append(const char* str, const char* str_end)
2568
0
{
2569
0
    int len = str_end ? (int)(str_end - str) : (int)strlen(str);
2570
2571
    // Add zero-terminator the first time
2572
0
    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2573
0
    const int needed_sz = write_off + len;
2574
0
    if (write_off + len >= Buf.Capacity)
2575
0
    {
2576
0
        int new_capacity = Buf.Capacity * 2;
2577
0
        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2578
0
    }
2579
2580
0
    Buf.resize(needed_sz);
2581
0
    memcpy(&Buf[write_off - 1], str, (size_t)len);
2582
0
    Buf[write_off - 1 + len] = 0;
2583
0
}
2584
2585
void ImGuiTextBuffer::appendf(const char* fmt, ...)
2586
0
{
2587
0
    va_list args;
2588
0
    va_start(args, fmt);
2589
0
    appendfv(fmt, args);
2590
0
    va_end(args);
2591
0
}
2592
2593
// Helper: Text buffer for logging/accumulating text
2594
void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
2595
0
{
2596
0
    va_list args_copy;
2597
0
    va_copy(args_copy, args);
2598
2599
0
    int len = ImFormatStringV(NULL, 0, fmt, args);         // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
2600
0
    if (len <= 0)
2601
0
    {
2602
0
        va_end(args_copy);
2603
0
        return;
2604
0
    }
2605
2606
    // Add zero-terminator the first time
2607
0
    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2608
0
    const int needed_sz = write_off + len;
2609
0
    if (write_off + len >= Buf.Capacity)
2610
0
    {
2611
0
        int new_capacity = Buf.Capacity * 2;
2612
0
        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2613
0
    }
2614
2615
0
    Buf.resize(needed_sz);
2616
0
    ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
2617
0
    va_end(args_copy);
2618
0
}
2619
2620
void ImGuiTextIndex::append(const char* base, int old_size, int new_size)
2621
0
{
2622
0
    IM_ASSERT(old_size >= 0 && new_size >= old_size && new_size >= EndOffset);
2623
0
    if (old_size == new_size)
2624
0
        return;
2625
0
    if (EndOffset == 0 || base[EndOffset - 1] == '\n')
2626
0
        LineOffsets.push_back(EndOffset);
2627
0
    const char* base_end = base + new_size;
2628
0
    for (const char* p = base + old_size; (p = (const char*)memchr(p, '\n', base_end - p)) != 0; )
2629
0
        if (++p < base_end) // Don't push a trailing offset on last \n
2630
0
            LineOffsets.push_back((int)(intptr_t)(p - base));
2631
0
    EndOffset = ImMax(EndOffset, new_size);
2632
0
}
2633
2634
//-----------------------------------------------------------------------------
2635
// [SECTION] ImGuiListClipper
2636
// This is currently not as flexible/powerful as it should be and really confusing/spaghetti, mostly because we changed
2637
// the API mid-way through development and support two ways to using the clipper, needs some rework (see TODO)
2638
//-----------------------------------------------------------------------------
2639
2640
// FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell.
2641
// The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous.
2642
static bool GetSkipItemForListClipping()
2643
0
{
2644
0
    ImGuiContext& g = *GImGui;
2645
0
    return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems);
2646
0
}
2647
2648
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
2649
// Legacy helper to calculate coarse clipping of large list of evenly sized items.
2650
// This legacy API is not ideal because it assumes we will return a single contiguous rectangle.
2651
// Prefer using ImGuiListClipper which can returns non-contiguous ranges.
2652
void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end)
2653
{
2654
    ImGuiContext& g = *GImGui;
2655
    ImGuiWindow* window = g.CurrentWindow;
2656
    if (g.LogEnabled)
2657
    {
2658
        // If logging is active, do not perform any clipping
2659
        *out_items_display_start = 0;
2660
        *out_items_display_end = items_count;
2661
        return;
2662
    }
2663
    if (GetSkipItemForListClipping())
2664
    {
2665
        *out_items_display_start = *out_items_display_end = 0;
2666
        return;
2667
    }
2668
2669
    // We create the union of the ClipRect and the scoring rect which at worst should be 1 page away from ClipRect
2670
    // We don't include g.NavId's rectangle in there (unless g.NavJustMovedToId is set) because the rectangle enlargement can get costly.
2671
    ImRect rect = window->ClipRect;
2672
    if (g.NavMoveScoringItems)
2673
        rect.Add(g.NavScoringNoClipRect);
2674
    if (g.NavJustMovedToId && window->NavLastIds[0] == g.NavJustMovedToId)
2675
        rect.Add(WindowRectRelToAbs(window, window->NavRectRel[0])); // Could store and use NavJustMovedToRectRel
2676
2677
    const ImVec2 pos = window->DC.CursorPos;
2678
    int start = (int)((rect.Min.y - pos.y) / items_height);
2679
    int end = (int)((rect.Max.y - pos.y) / items_height);
2680
2681
    // When performing a navigation request, ensure we have one item extra in the direction we are moving to
2682
    // FIXME: Verify this works with tabbing
2683
    const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
2684
    if (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up)
2685
        start--;
2686
    if (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down)
2687
        end++;
2688
2689
    start = ImClamp(start, 0, items_count);
2690
    end = ImClamp(end + 1, start, items_count);
2691
    *out_items_display_start = start;
2692
    *out_items_display_end = end;
2693
}
2694
#endif
2695
2696
static void ImGuiListClipper_SortAndFuseRanges(ImVector<ImGuiListClipperRange>& ranges, int offset = 0)
2697
0
{
2698
0
    if (ranges.Size - offset <= 1)
2699
0
        return;
2700
2701
    // Helper to order ranges and fuse them together if possible (bubble sort is fine as we are only sorting 2-3 entries)
2702
0
    for (int sort_end = ranges.Size - offset - 1; sort_end > 0; --sort_end)
2703
0
        for (int i = offset; i < sort_end + offset; ++i)
2704
0
            if (ranges[i].Min > ranges[i + 1].Min)
2705
0
                ImSwap(ranges[i], ranges[i + 1]);
2706
2707
    // Now fuse ranges together as much as possible.
2708
0
    for (int i = 1 + offset; i < ranges.Size; i++)
2709
0
    {
2710
0
        IM_ASSERT(!ranges[i].PosToIndexConvert && !ranges[i - 1].PosToIndexConvert);
2711
0
        if (ranges[i - 1].Max < ranges[i].Min)
2712
0
            continue;
2713
0
        ranges[i - 1].Min = ImMin(ranges[i - 1].Min, ranges[i].Min);
2714
0
        ranges[i - 1].Max = ImMax(ranges[i - 1].Max, ranges[i].Max);
2715
0
        ranges.erase(ranges.Data + i);
2716
0
        i--;
2717
0
    }
2718
0
}
2719
2720
static void ImGuiListClipper_SeekCursorAndSetupPrevLine(float pos_y, float line_height)
2721
0
{
2722
    // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
2723
    // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
2724
    // The clipper should probably have a final step to display the last item in a regular manner, maybe with an opt-out flag for data sets which may have costly seek?
2725
0
    ImGuiContext& g = *GImGui;
2726
0
    ImGuiWindow* window = g.CurrentWindow;
2727
0
    float off_y = pos_y - window->DC.CursorPos.y;
2728
0
    window->DC.CursorPos.y = pos_y;
2729
0
    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y - g.Style.ItemSpacing.y);
2730
0
    window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height;  // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage.
2731
0
    window->DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y);      // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
2732
0
    if (ImGuiOldColumns* columns = window->DC.CurrentColumns)
2733
0
        columns->LineMinY = window->DC.CursorPos.y;                         // Setting this so that cell Y position are set properly
2734
0
    if (ImGuiTable* table = g.CurrentTable)
2735
0
    {
2736
0
        if (table->IsInsideRow)
2737
0
            ImGui::TableEndRow(table);
2738
0
        table->RowPosY2 = window->DC.CursorPos.y;
2739
0
        const int row_increase = (int)((off_y / line_height) + 0.5f);
2740
        //table->CurrentRow += row_increase; // Can't do without fixing TableEndRow()
2741
0
        table->RowBgColorCounter += row_increase;
2742
0
    }
2743
0
}
2744
2745
static void ImGuiListClipper_SeekCursorForItem(ImGuiListClipper* clipper, int item_n)
2746
0
{
2747
    // StartPosY starts from ItemsFrozen hence the subtraction
2748
    // Perform the add and multiply with double to allow seeking through larger ranges
2749
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
2750
0
    float pos_y = (float)((double)clipper->StartPosY + data->LossynessOffset + (double)(item_n - data->ItemsFrozen) * clipper->ItemsHeight);
2751
0
    ImGuiListClipper_SeekCursorAndSetupPrevLine(pos_y, clipper->ItemsHeight);
2752
0
}
2753
2754
ImGuiListClipper::ImGuiListClipper()
2755
0
{
2756
0
    memset(this, 0, sizeof(*this));
2757
0
    ItemsCount = -1;
2758
0
}
2759
2760
ImGuiListClipper::~ImGuiListClipper()
2761
0
{
2762
0
    End();
2763
0
}
2764
2765
void ImGuiListClipper::Begin(int items_count, float items_height)
2766
0
{
2767
0
    ImGuiContext& g = *GImGui;
2768
0
    ImGuiWindow* window = g.CurrentWindow;
2769
0
    IMGUI_DEBUG_LOG_CLIPPER("Clipper: Begin(%d,%.2f) in '%s'\n", items_count, items_height, window->Name);
2770
2771
0
    if (ImGuiTable* table = g.CurrentTable)
2772
0
        if (table->IsInsideRow)
2773
0
            ImGui::TableEndRow(table);
2774
2775
0
    StartPosY = window->DC.CursorPos.y;
2776
0
    ItemsHeight = items_height;
2777
0
    ItemsCount = items_count;
2778
0
    DisplayStart = -1;
2779
0
    DisplayEnd = 0;
2780
2781
    // Acquire temporary buffer
2782
0
    if (++g.ClipperTempDataStacked > g.ClipperTempData.Size)
2783
0
        g.ClipperTempData.resize(g.ClipperTempDataStacked, ImGuiListClipperData());
2784
0
    ImGuiListClipperData* data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
2785
0
    data->Reset(this);
2786
0
    data->LossynessOffset = window->DC.CursorStartPosLossyness.y;
2787
0
    TempData = data;
2788
0
}
2789
2790
void ImGuiListClipper::End()
2791
0
{
2792
0
    ImGuiContext& g = *GImGui;
2793
0
    if (ImGuiListClipperData* data = (ImGuiListClipperData*)TempData)
2794
0
    {
2795
        // In theory here we should assert that we are already at the right position, but it seems saner to just seek at the end and not assert/crash the user.
2796
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: End() in '%s'\n", g.CurrentWindow->Name);
2797
0
        if (ItemsCount >= 0 && ItemsCount < INT_MAX && DisplayStart >= 0)
2798
0
            ImGuiListClipper_SeekCursorForItem(this, ItemsCount);
2799
2800
        // Restore temporary buffer and fix back pointers which may be invalidated when nesting
2801
0
        IM_ASSERT(data->ListClipper == this);
2802
0
        data->StepNo = data->Ranges.Size;
2803
0
        if (--g.ClipperTempDataStacked > 0)
2804
0
        {
2805
0
            data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
2806
0
            data->ListClipper->TempData = data;
2807
0
        }
2808
0
        TempData = NULL;
2809
0
    }
2810
0
    ItemsCount = -1;
2811
0
}
2812
2813
void ImGuiListClipper::ForceDisplayRangeByIndices(int item_min, int item_max)
2814
0
{
2815
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)TempData;
2816
0
    IM_ASSERT(DisplayStart < 0); // Only allowed after Begin() and if there has not been a specified range yet.
2817
0
    IM_ASSERT(item_min <= item_max);
2818
0
    if (item_min < item_max)
2819
0
        data->Ranges.push_back(ImGuiListClipperRange::FromIndices(item_min, item_max));
2820
0
}
2821
2822
static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper)
2823
0
{
2824
0
    ImGuiContext& g = *GImGui;
2825
0
    ImGuiWindow* window = g.CurrentWindow;
2826
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
2827
0
    IM_ASSERT(data != NULL && "Called ImGuiListClipper::Step() too many times, or before ImGuiListClipper::Begin() ?");
2828
2829
0
    ImGuiTable* table = g.CurrentTable;
2830
0
    if (table && table->IsInsideRow)
2831
0
        ImGui::TableEndRow(table);
2832
2833
    // No items
2834
0
    if (clipper->ItemsCount == 0 || GetSkipItemForListClipping())
2835
0
        return false;
2836
2837
    // While we are in frozen row state, keep displaying items one by one, unclipped
2838
    // FIXME: Could be stored as a table-agnostic state.
2839
0
    if (data->StepNo == 0 && table != NULL && !table->IsUnfrozenRows)
2840
0
    {
2841
0
        clipper->DisplayStart = data->ItemsFrozen;
2842
0
        clipper->DisplayEnd = ImMin(data->ItemsFrozen + 1, clipper->ItemsCount);
2843
0
        if (clipper->DisplayStart < clipper->DisplayEnd)
2844
0
            data->ItemsFrozen++;
2845
0
        return true;
2846
0
    }
2847
2848
    // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height)
2849
0
    bool calc_clipping = false;
2850
0
    if (data->StepNo == 0)
2851
0
    {
2852
0
        clipper->StartPosY = window->DC.CursorPos.y;
2853
0
        if (clipper->ItemsHeight <= 0.0f)
2854
0
        {
2855
            // Submit the first item (or range) so we can measure its height (generally the first range is 0..1)
2856
0
            data->Ranges.push_front(ImGuiListClipperRange::FromIndices(data->ItemsFrozen, data->ItemsFrozen + 1));
2857
0
            clipper->DisplayStart = ImMax(data->Ranges[0].Min, data->ItemsFrozen);
2858
0
            clipper->DisplayEnd = ImMin(data->Ranges[0].Max, clipper->ItemsCount);
2859
0
            data->StepNo = 1;
2860
0
            return true;
2861
0
        }
2862
0
        calc_clipping = true;   // If on the first step with known item height, calculate clipping.
2863
0
    }
2864
2865
    // Step 1: Let the clipper infer height from first range
2866
0
    if (clipper->ItemsHeight <= 0.0f)
2867
0
    {
2868
0
        IM_ASSERT(data->StepNo == 1);
2869
0
        if (table)
2870
0
            IM_ASSERT(table->RowPosY1 == clipper->StartPosY && table->RowPosY2 == window->DC.CursorPos.y);
2871
2872
0
        clipper->ItemsHeight = (window->DC.CursorPos.y - clipper->StartPosY) / (float)(clipper->DisplayEnd - clipper->DisplayStart);
2873
0
        bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision(clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(window->DC.CursorPos.y);
2874
0
        if (affected_by_floating_point_precision)
2875
0
            clipper->ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries.
2876
2877
0
        IM_ASSERT(clipper->ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!");
2878
0
        calc_clipping = true;   // If item height had to be calculated, calculate clipping afterwards.
2879
0
    }
2880
2881
    // Step 0 or 1: Calculate the actual ranges of visible elements.
2882
0
    const int already_submitted = clipper->DisplayEnd;
2883
0
    if (calc_clipping)
2884
0
    {
2885
0
        if (g.LogEnabled)
2886
0
        {
2887
            // If logging is active, do not perform any clipping
2888
0
            data->Ranges.push_back(ImGuiListClipperRange::FromIndices(0, clipper->ItemsCount));
2889
0
        }
2890
0
        else
2891
0
        {
2892
            // Add range selected to be included for navigation
2893
0
            const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
2894
0
            if (is_nav_request)
2895
0
                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringNoClipRect.Min.y, g.NavScoringNoClipRect.Max.y, 0, 0));
2896
0
            if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) && g.NavTabbingDir == -1)
2897
0
                data->Ranges.push_back(ImGuiListClipperRange::FromIndices(clipper->ItemsCount - 1, clipper->ItemsCount));
2898
2899
            // Add focused/active item
2900
0
            ImRect nav_rect_abs = ImGui::WindowRectRelToAbs(window, window->NavRectRel[0]);
2901
0
            if (g.NavId != 0 && window->NavLastIds[0] == g.NavId)
2902
0
                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(nav_rect_abs.Min.y, nav_rect_abs.Max.y, 0, 0));
2903
2904
            // Add visible range
2905
0
            const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0;
2906
0
            const int off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0;
2907
0
            data->Ranges.push_back(ImGuiListClipperRange::FromPositions(window->ClipRect.Min.y, window->ClipRect.Max.y, off_min, off_max));
2908
0
        }
2909
2910
        // Convert position ranges to item index ranges
2911
        // - Very important: when a starting position is after our maximum item, we set Min to (ItemsCount - 1). This allows us to handle most forms of wrapping.
2912
        // - Due to how Selectable extra padding they tend to be "unaligned" with exact unit in the item list,
2913
        //   which with the flooring/ceiling tend to lead to 2 items instead of one being submitted.
2914
0
        for (int i = 0; i < data->Ranges.Size; i++)
2915
0
            if (data->Ranges[i].PosToIndexConvert)
2916
0
            {
2917
0
                int m1 = (int)(((double)data->Ranges[i].Min - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight);
2918
0
                int m2 = (int)((((double)data->Ranges[i].Max - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight) + 0.999999f);
2919
0
                data->Ranges[i].Min = ImClamp(already_submitted + m1 + data->Ranges[i].PosToIndexOffsetMin, already_submitted, clipper->ItemsCount - 1);
2920
0
                data->Ranges[i].Max = ImClamp(already_submitted + m2 + data->Ranges[i].PosToIndexOffsetMax, data->Ranges[i].Min + 1, clipper->ItemsCount);
2921
0
                data->Ranges[i].PosToIndexConvert = false;
2922
0
            }
2923
0
        ImGuiListClipper_SortAndFuseRanges(data->Ranges, data->StepNo);
2924
0
    }
2925
2926
    // Step 0+ (if item height is given in advance) or 1+: Display the next range in line.
2927
0
    if (data->StepNo < data->Ranges.Size)
2928
0
    {
2929
0
        clipper->DisplayStart = ImMax(data->Ranges[data->StepNo].Min, already_submitted);
2930
0
        clipper->DisplayEnd = ImMin(data->Ranges[data->StepNo].Max, clipper->ItemsCount);
2931
0
        if (clipper->DisplayStart > already_submitted) //-V1051
2932
0
            ImGuiListClipper_SeekCursorForItem(clipper, clipper->DisplayStart);
2933
0
        data->StepNo++;
2934
0
        return true;
2935
0
    }
2936
2937
    // After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd),
2938
    // Advance the cursor to the end of the list and then returns 'false' to end the loop.
2939
0
    if (clipper->ItemsCount < INT_MAX)
2940
0
        ImGuiListClipper_SeekCursorForItem(clipper, clipper->ItemsCount);
2941
2942
0
    return false;
2943
0
}
2944
2945
bool ImGuiListClipper::Step()
2946
0
{
2947
0
    ImGuiContext& g = *GImGui;
2948
0
    bool need_items_height = (ItemsHeight <= 0.0f);
2949
0
    bool ret = ImGuiListClipper_StepInternal(this);
2950
0
    if (ret && (DisplayStart == DisplayEnd))
2951
0
        ret = false;
2952
0
    if (g.CurrentTable && g.CurrentTable->IsUnfrozenRows == false)
2953
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): inside frozen table row.\n");
2954
0
    if (need_items_height && ItemsHeight > 0.0f)
2955
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): computed ItemsHeight: %.2f.\n", ItemsHeight);
2956
0
    if (ret)
2957
0
    {
2958
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): display %d to %d.\n", DisplayStart, DisplayEnd);
2959
0
    }
2960
0
    else
2961
0
    {
2962
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): End.\n");
2963
0
        End();
2964
0
    }
2965
0
    return ret;
2966
0
}
2967
2968
//-----------------------------------------------------------------------------
2969
// [SECTION] STYLING
2970
//-----------------------------------------------------------------------------
2971
2972
ImGuiStyle& ImGui::GetStyle()
2973
10.8k
{
2974
10.8k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
2975
10.8k
    return GImGui->Style;
2976
10.8k
}
2977
2978
ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
2979
51.3k
{
2980
51.3k
    ImGuiStyle& style = GImGui->Style;
2981
51.3k
    ImVec4 c = style.Colors[idx];
2982
51.3k
    c.w *= style.Alpha * alpha_mul;
2983
51.3k
    return ColorConvertFloat4ToU32(c);
2984
51.3k
}
2985
2986
ImU32 ImGui::GetColorU32(const ImVec4& col)
2987
0
{
2988
0
    ImGuiStyle& style = GImGui->Style;
2989
0
    ImVec4 c = col;
2990
0
    c.w *= style.Alpha;
2991
0
    return ColorConvertFloat4ToU32(c);
2992
0
}
2993
2994
const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
2995
0
{
2996
0
    ImGuiStyle& style = GImGui->Style;
2997
0
    return style.Colors[idx];
2998
0
}
2999
3000
ImU32 ImGui::GetColorU32(ImU32 col)
3001
0
{
3002
0
    ImGuiStyle& style = GImGui->Style;
3003
0
    if (style.Alpha >= 1.0f)
3004
0
        return col;
3005
0
    ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
3006
0
    a = (ImU32)(a * style.Alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range.
3007
0
    return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
3008
0
}
3009
3010
// FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32
3011
void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
3012
0
{
3013
0
    ImGuiContext& g = *GImGui;
3014
0
    ImGuiColorMod backup;
3015
0
    backup.Col = idx;
3016
0
    backup.BackupValue = g.Style.Colors[idx];
3017
0
    g.ColorStack.push_back(backup);
3018
0
    g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
3019
0
}
3020
3021
void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
3022
3.00k
{
3023
3.00k
    ImGuiContext& g = *GImGui;
3024
3.00k
    ImGuiColorMod backup;
3025
3.00k
    backup.Col = idx;
3026
3.00k
    backup.BackupValue = g.Style.Colors[idx];
3027
3.00k
    g.ColorStack.push_back(backup);
3028
3.00k
    g.Style.Colors[idx] = col;
3029
3.00k
}
3030
3031
void ImGui::PopStyleColor(int count)
3032
3.00k
{
3033
3.00k
    ImGuiContext& g = *GImGui;
3034
3.00k
    if (g.ColorStack.Size < count)
3035
0
    {
3036
0
        IM_ASSERT_USER_ERROR(g.ColorStack.Size > count, "Calling PopStyleColor() too many times: stack underflow.");
3037
0
        count = g.ColorStack.Size;
3038
0
    }
3039
6.00k
    while (count > 0)
3040
3.00k
    {
3041
3.00k
        ImGuiColorMod& backup = g.ColorStack.back();
3042
3.00k
        g.Style.Colors[backup.Col] = backup.BackupValue;
3043
3.00k
        g.ColorStack.pop_back();
3044
3.00k
        count--;
3045
3.00k
    }
3046
3.00k
}
3047
3048
struct ImGuiStyleVarInfo
3049
{
3050
    ImGuiDataType   Type;
3051
    ImU32           Count;
3052
    ImU32           Offset;
3053
6.00k
    void*           GetVarPtr(ImGuiStyle* style) const { return (void*)((unsigned char*)style + Offset); }
3054
};
3055
3056
static const ImGuiCol GWindowDockStyleColors[ImGuiWindowDockStyleCol_COUNT] =
3057
{
3058
    ImGuiCol_Text, ImGuiCol_Tab, ImGuiCol_TabHovered, ImGuiCol_TabActive, ImGuiCol_TabUnfocused, ImGuiCol_TabUnfocusedActive
3059
};
3060
3061
static const ImGuiStyleVarInfo GStyleVarInfo[] =
3062
{
3063
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) },               // ImGuiStyleVar_Alpha
3064
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, DisabledAlpha) },       // ImGuiStyleVar_DisabledAlpha
3065
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) },       // ImGuiStyleVar_WindowPadding
3066
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) },      // ImGuiStyleVar_WindowRounding
3067
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowBorderSize) },    // ImGuiStyleVar_WindowBorderSize
3068
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) },       // ImGuiStyleVar_WindowMinSize
3069
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowTitleAlign) },    // ImGuiStyleVar_WindowTitleAlign
3070
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildRounding) },       // ImGuiStyleVar_ChildRounding
3071
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildBorderSize) },     // ImGuiStyleVar_ChildBorderSize
3072
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupRounding) },       // ImGuiStyleVar_PopupRounding
3073
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupBorderSize) },     // ImGuiStyleVar_PopupBorderSize
3074
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) },        // ImGuiStyleVar_FramePadding
3075
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) },       // ImGuiStyleVar_FrameRounding
3076
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameBorderSize) },     // ImGuiStyleVar_FrameBorderSize
3077
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) },         // ImGuiStyleVar_ItemSpacing
3078
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) },    // ImGuiStyleVar_ItemInnerSpacing
3079
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) },       // ImGuiStyleVar_IndentSpacing
3080
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, CellPadding) },         // ImGuiStyleVar_CellPadding
3081
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize) },       // ImGuiStyleVar_ScrollbarSize
3082
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding) },   // ImGuiStyleVar_ScrollbarRounding
3083
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) },         // ImGuiStyleVar_GrabMinSize
3084
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabRounding) },        // ImGuiStyleVar_GrabRounding
3085
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, TabRounding) },         // ImGuiStyleVar_TabRounding
3086
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) },     // ImGuiStyleVar_ButtonTextAlign
3087
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign
3088
};
3089
3090
static const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx)
3091
6.00k
{
3092
6.00k
    IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
3093
6.00k
    IM_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
3094
6.00k
    return &GStyleVarInfo[idx];
3095
6.00k
}
3096
3097
void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
3098
0
{
3099
0
    const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
3100
0
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)
3101
0
    {
3102
0
        ImGuiContext& g = *GImGui;
3103
0
        float* pvar = (float*)var_info->GetVarPtr(&g.Style);
3104
0
        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3105
0
        *pvar = val;
3106
0
        return;
3107
0
    }
3108
0
    IM_ASSERT(0 && "Called PushStyleVar() float variant but variable is not a float!");
3109
0
}
3110
3111
void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
3112
3.00k
{
3113
3.00k
    const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
3114
3.00k
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
3115
3.00k
    {
3116
3.00k
        ImGuiContext& g = *GImGui;
3117
3.00k
        ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
3118
3.00k
        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3119
3.00k
        *pvar = val;
3120
3.00k
        return;
3121
3.00k
    }
3122
0
    IM_ASSERT(0 && "Called PushStyleVar() ImVec2 variant but variable is not a ImVec2!");
3123
0
}
3124
3125
void ImGui::PopStyleVar(int count)
3126
3.00k
{
3127
3.00k
    ImGuiContext& g = *GImGui;
3128
3.00k
    if (g.StyleVarStack.Size < count)
3129
0
    {
3130
0
        IM_ASSERT_USER_ERROR(g.StyleVarStack.Size > count, "Calling PopStyleVar() too many times: stack underflow.");
3131
0
        count = g.StyleVarStack.Size;
3132
0
    }
3133
6.00k
    while (count > 0)
3134
3.00k
    {
3135
        // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
3136
3.00k
        ImGuiStyleMod& backup = g.StyleVarStack.back();
3137
3.00k
        const ImGuiStyleVarInfo* info = GetStyleVarInfo(backup.VarIdx);
3138
3.00k
        void* data = info->GetVarPtr(&g.Style);
3139
3.00k
        if (info->Type == ImGuiDataType_Float && info->Count == 1)      { ((float*)data)[0] = backup.BackupFloat[0]; }
3140
3.00k
        else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
3141
3.00k
        g.StyleVarStack.pop_back();
3142
3.00k
        count--;
3143
3.00k
    }
3144
3.00k
}
3145
3146
const char* ImGui::GetStyleColorName(ImGuiCol idx)
3147
0
{
3148
    // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
3149
0
    switch (idx)
3150
0
    {
3151
0
    case ImGuiCol_Text: return "Text";
3152
0
    case ImGuiCol_TextDisabled: return "TextDisabled";
3153
0
    case ImGuiCol_WindowBg: return "WindowBg";
3154
0
    case ImGuiCol_ChildBg: return "ChildBg";
3155
0
    case ImGuiCol_PopupBg: return "PopupBg";
3156
0
    case ImGuiCol_Border: return "Border";
3157
0
    case ImGuiCol_BorderShadow: return "BorderShadow";
3158
0
    case ImGuiCol_FrameBg: return "FrameBg";
3159
0
    case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
3160
0
    case ImGuiCol_FrameBgActive: return "FrameBgActive";
3161
0
    case ImGuiCol_TitleBg: return "TitleBg";
3162
0
    case ImGuiCol_TitleBgActive: return "TitleBgActive";
3163
0
    case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
3164
0
    case ImGuiCol_MenuBarBg: return "MenuBarBg";
3165
0
    case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
3166
0
    case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
3167
0
    case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
3168
0
    case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
3169
0
    case ImGuiCol_CheckMark: return "CheckMark";
3170
0
    case ImGuiCol_SliderGrab: return "SliderGrab";
3171
0
    case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
3172
0
    case ImGuiCol_Button: return "Button";
3173
0
    case ImGuiCol_ButtonHovered: return "ButtonHovered";
3174
0
    case ImGuiCol_ButtonActive: return "ButtonActive";
3175
0
    case ImGuiCol_Header: return "Header";
3176
0
    case ImGuiCol_HeaderHovered: return "HeaderHovered";
3177
0
    case ImGuiCol_HeaderActive: return "HeaderActive";
3178
0
    case ImGuiCol_Separator: return "Separator";
3179
0
    case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
3180
0
    case ImGuiCol_SeparatorActive: return "SeparatorActive";
3181
0
    case ImGuiCol_ResizeGrip: return "ResizeGrip";
3182
0
    case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
3183
0
    case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
3184
0
    case ImGuiCol_Tab: return "Tab";
3185
0
    case ImGuiCol_TabHovered: return "TabHovered";
3186
0
    case ImGuiCol_TabActive: return "TabActive";
3187
0
    case ImGuiCol_TabUnfocused: return "TabUnfocused";
3188
0
    case ImGuiCol_TabUnfocusedActive: return "TabUnfocusedActive";
3189
0
    case ImGuiCol_DockingPreview: return "DockingPreview";
3190
0
    case ImGuiCol_DockingEmptyBg: return "DockingEmptyBg";
3191
0
    case ImGuiCol_PlotLines: return "PlotLines";
3192
0
    case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
3193
0
    case ImGuiCol_PlotHistogram: return "PlotHistogram";
3194
0
    case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
3195
0
    case ImGuiCol_TableHeaderBg: return "TableHeaderBg";
3196
0
    case ImGuiCol_TableBorderStrong: return "TableBorderStrong";
3197
0
    case ImGuiCol_TableBorderLight: return "TableBorderLight";
3198
0
    case ImGuiCol_TableRowBg: return "TableRowBg";
3199
0
    case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt";
3200
0
    case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
3201
0
    case ImGuiCol_DragDropTarget: return "DragDropTarget";
3202
0
    case ImGuiCol_NavHighlight: return "NavHighlight";
3203
0
    case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
3204
0
    case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
3205
0
    case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
3206
0
    }
3207
0
    IM_ASSERT(0);
3208
0
    return "Unknown";
3209
0
}
3210
3211
3212
//-----------------------------------------------------------------------------
3213
// [SECTION] RENDER HELPERS
3214
// Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
3215
// we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.
3216
// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.
3217
//-----------------------------------------------------------------------------
3218
3219
const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
3220
12.0k
{
3221
12.0k
    const char* text_display_end = text;
3222
12.0k
    if (!text_end)
3223
12.0k
        text_end = (const char*)-1;
3224
3225
108k
    while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
3226
96.0k
        text_display_end++;
3227
12.0k
    return text_display_end;
3228
12.0k
}
3229
3230
// Internal ImGui functions to render text
3231
// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
3232
void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
3233
0
{
3234
0
    ImGuiContext& g = *GImGui;
3235
0
    ImGuiWindow* window = g.CurrentWindow;
3236
3237
    // Hide anything after a '##' string
3238
0
    const char* text_display_end;
3239
0
    if (hide_text_after_hash)
3240
0
    {
3241
0
        text_display_end = FindRenderedTextEnd(text, text_end);
3242
0
    }
3243
0
    else
3244
0
    {
3245
0
        if (!text_end)
3246
0
            text_end = text + strlen(text); // FIXME-OPT
3247
0
        text_display_end = text_end;
3248
0
    }
3249
3250
0
    if (text != text_display_end)
3251
0
    {
3252
0
        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
3253
0
        if (g.LogEnabled)
3254
0
            LogRenderedText(&pos, text, text_display_end);
3255
0
    }
3256
0
}
3257
3258
void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
3259
0
{
3260
0
    ImGuiContext& g = *GImGui;
3261
0
    ImGuiWindow* window = g.CurrentWindow;
3262
3263
0
    if (!text_end)
3264
0
        text_end = text + strlen(text); // FIXME-OPT
3265
3266
0
    if (text != text_end)
3267
0
    {
3268
0
        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
3269
0
        if (g.LogEnabled)
3270
0
            LogRenderedText(&pos, text, text_end);
3271
0
    }
3272
0
}
3273
3274
// Default clip_rect uses (pos_min,pos_max)
3275
// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
3276
void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3277
6.00k
{
3278
    // Perform CPU side clipping for single clipped element to avoid using scissor state
3279
6.00k
    ImVec2 pos = pos_min;
3280
6.00k
    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
3281
3282
6.00k
    const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
3283
6.00k
    const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
3284
6.00k
    bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
3285
6.00k
    if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
3286
6.00k
        need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
3287
3288
    // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
3289
6.00k
    if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
3290
6.00k
    if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
3291
3292
    // Render
3293
6.00k
    if (need_clipping)
3294
3.00k
    {
3295
3.00k
        ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
3296
3.00k
        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
3297
3.00k
    }
3298
3.00k
    else
3299
3.00k
    {
3300
3.00k
        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
3301
3.00k
    }
3302
6.00k
}
3303
3304
void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3305
6.00k
{
3306
    // Hide anything after a '##' string
3307
6.00k
    const char* text_display_end = FindRenderedTextEnd(text, text_end);
3308
6.00k
    const int text_len = (int)(text_display_end - text);
3309
6.00k
    if (text_len == 0)
3310
0
        return;
3311
3312
6.00k
    ImGuiContext& g = *GImGui;
3313
6.00k
    ImGuiWindow* window = g.CurrentWindow;
3314
6.00k
    RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
3315
6.00k
    if (g.LogEnabled)
3316
0
        LogRenderedText(&pos_min, text, text_display_end);
3317
6.00k
}
3318
3319
// Another overly complex function until we reorganize everything into a nice all-in-one helper.
3320
// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define _where_ the ellipsis is, from actual clipping of text and limit of the ellipsis display.
3321
// This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move.
3322
void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known)
3323
0
{
3324
0
    ImGuiContext& g = *GImGui;
3325
0
    if (text_end_full == NULL)
3326
0
        text_end_full = FindRenderedTextEnd(text);
3327
0
    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f);
3328
3329
    //draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 4), IM_COL32(0, 0, 255, 255));
3330
    //draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y-2), ImVec2(ellipsis_max_x, pos_max.y+2), IM_COL32(0, 255, 0, 255));
3331
    //draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255));
3332
    // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
3333
0
    if (text_size.x > pos_max.x - pos_min.x)
3334
0
    {
3335
        // Hello wo...
3336
        // |       |   |
3337
        // min   max   ellipsis_max
3338
        //          <-> this is generally some padding value
3339
3340
0
        const ImFont* font = draw_list->_Data->Font;
3341
0
        const float font_size = draw_list->_Data->FontSize;
3342
0
        const float font_scale = font_size / font->FontSize;
3343
0
        const char* text_end_ellipsis = NULL;
3344
0
        const float ellipsis_width = font->EllipsisWidth * font_scale;
3345
3346
        // We can now claim the space between pos_max.x and ellipsis_max.x
3347
0
        const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_width) - pos_min.x, 1.0f);
3348
0
        float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x;
3349
0
        if (text == text_end_ellipsis && text_end_ellipsis < text_end_full)
3350
0
        {
3351
            // Always display at least 1 character if there's no room for character + ellipsis
3352
0
            text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full);
3353
0
            text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x;
3354
0
        }
3355
0
        while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1]))
3356
0
        {
3357
            // Trim trailing space before ellipsis (FIXME: Supporting non-ascii blanks would be nice, for this we need a function to backtrack in UTF-8 text)
3358
0
            text_end_ellipsis--;
3359
0
            text_size_clipped_x -= font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text_end_ellipsis, text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte
3360
0
        }
3361
3362
        // Render text, render ellipsis
3363
0
        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));
3364
0
        ImVec2 ellipsis_pos = ImFloor(ImVec2(pos_min.x + text_size_clipped_x, pos_min.y));
3365
0
        if (ellipsis_pos.x + ellipsis_width <= ellipsis_max_x)
3366
0
            for (int i = 0; i < font->EllipsisCharCount; i++, ellipsis_pos.x += font->EllipsisCharStep * font_scale)
3367
0
                font->RenderChar(draw_list, font_size, ellipsis_pos, GetColorU32(ImGuiCol_Text), font->EllipsisChar);
3368
0
    }
3369
0
    else
3370
0
    {
3371
0
        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));
3372
0
    }
3373
3374
0
    if (g.LogEnabled)
3375
0
        LogRenderedText(&pos_min, text, text_end_full);
3376
0
}
3377
3378
// Render a rectangle shaped with optional rounding and borders
3379
void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
3380
0
{
3381
0
    ImGuiContext& g = *GImGui;
3382
0
    ImGuiWindow* window = g.CurrentWindow;
3383
0
    window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
3384
0
    const float border_size = g.Style.FrameBorderSize;
3385
0
    if (border && border_size > 0.0f)
3386
0
    {
3387
0
        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3388
0
        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3389
0
    }
3390
0
}
3391
3392
void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
3393
0
{
3394
0
    ImGuiContext& g = *GImGui;
3395
0
    ImGuiWindow* window = g.CurrentWindow;
3396
0
    const float border_size = g.Style.FrameBorderSize;
3397
0
    if (border_size > 0.0f)
3398
0
    {
3399
0
        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3400
0
        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3401
0
    }
3402
0
}
3403
3404
void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
3405
5.38k
{
3406
5.38k
    ImGuiContext& g = *GImGui;
3407
5.38k
    if (id != g.NavId)
3408
2.90k
        return;
3409
2.48k
    if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
3410
716
        return;
3411
1.76k
    ImGuiWindow* window = g.CurrentWindow;
3412
1.76k
    if (window->DC.NavHideHighlightOneFrame)
3413
0
        return;
3414
3415
1.76k
    float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
3416
1.76k
    ImRect display_rect = bb;
3417
1.76k
    display_rect.ClipWith(window->ClipRect);
3418
1.76k
    if (flags & ImGuiNavHighlightFlags_TypeDefault)
3419
0
    {
3420
0
        const float THICKNESS = 2.0f;
3421
0
        const float DISTANCE = 3.0f + THICKNESS * 0.5f;
3422
0
        display_rect.Expand(ImVec2(DISTANCE, DISTANCE));
3423
0
        bool fully_visible = window->ClipRect.Contains(display_rect);
3424
0
        if (!fully_visible)
3425
0
            window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
3426
0
        window->DrawList->AddRect(display_rect.Min + ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), display_rect.Max - ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), GetColorU32(ImGuiCol_NavHighlight), rounding, 0, THICKNESS);
3427
0
        if (!fully_visible)
3428
0
            window->DrawList->PopClipRect();
3429
0
    }
3430
1.76k
    if (flags & ImGuiNavHighlightFlags_TypeThin)
3431
1.76k
    {
3432
1.76k
        window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, 1.0f);
3433
1.76k
    }
3434
1.76k
}
3435
3436
void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow)
3437
0
{
3438
0
    ImGuiContext& g = *GImGui;
3439
0
    IM_ASSERT(mouse_cursor > ImGuiMouseCursor_None && mouse_cursor < ImGuiMouseCursor_COUNT);
3440
0
    ImFontAtlas* font_atlas = g.DrawListSharedData.Font->ContainerAtlas;
3441
0
    for (int n = 0; n < g.Viewports.Size; n++)
3442
0
    {
3443
        // We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor.
3444
0
        ImVec2 offset, size, uv[4];
3445
0
        if (!font_atlas->GetMouseCursorTexData(mouse_cursor, &offset, &size, &uv[0], &uv[2]))
3446
0
            continue;
3447
0
        ImGuiViewportP* viewport = g.Viewports[n];
3448
0
        const ImVec2 pos = base_pos - offset;
3449
0
        const float scale = base_scale * viewport->DpiScale;
3450
0
        if (!viewport->GetMainRect().Overlaps(ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale)))
3451
0
            continue;
3452
0
        ImDrawList* draw_list = GetForegroundDrawList(viewport);
3453
0
        ImTextureID tex_id = font_atlas->TexID;
3454
0
        draw_list->PushTextureID(tex_id);
3455
0
        draw_list->AddImage(tex_id, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale, uv[2], uv[3], col_shadow);
3456
0
        draw_list->AddImage(tex_id, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv[2], uv[3], col_shadow);
3457
0
        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                  uv[2], uv[3], col_border);
3458
0
        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                  uv[0], uv[1], col_fill);
3459
0
        draw_list->PopTextureID();
3460
0
    }
3461
0
}
3462
3463
//-----------------------------------------------------------------------------
3464
// [SECTION] INITIALIZATION, SHUTDOWN
3465
//-----------------------------------------------------------------------------
3466
3467
// Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
3468
// Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module
3469
ImGuiContext* ImGui::GetCurrentContext()
3470
1
{
3471
1
    return GImGui;
3472
1
}
3473
3474
void ImGui::SetCurrentContext(ImGuiContext* ctx)
3475
1
{
3476
#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
3477
    IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
3478
#else
3479
1
    GImGui = ctx;
3480
1
#endif
3481
1
}
3482
3483
void ImGui::SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data)
3484
0
{
3485
0
    GImAllocatorAllocFunc = alloc_func;
3486
0
    GImAllocatorFreeFunc = free_func;
3487
0
    GImAllocatorUserData = user_data;
3488
0
}
3489
3490
// This is provided to facilitate copying allocators from one static/DLL boundary to another (e.g. retrieve default allocator of your executable address space)
3491
void ImGui::GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data)
3492
0
{
3493
0
    *p_alloc_func = GImAllocatorAllocFunc;
3494
0
    *p_free_func = GImAllocatorFreeFunc;
3495
0
    *p_user_data = GImAllocatorUserData;
3496
0
}
3497
3498
ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
3499
1
{
3500
1
    ImGuiContext* prev_ctx = GetCurrentContext();
3501
1
    ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
3502
1
    SetCurrentContext(ctx);
3503
1
    Initialize();
3504
1
    if (prev_ctx != NULL)
3505
0
        SetCurrentContext(prev_ctx); // Restore previous context if any, else keep new one.
3506
1
    return ctx;
3507
1
}
3508
3509
void ImGui::DestroyContext(ImGuiContext* ctx)
3510
0
{
3511
0
    ImGuiContext* prev_ctx = GetCurrentContext();
3512
0
    if (ctx == NULL) //-V1051
3513
0
        ctx = prev_ctx;
3514
0
    SetCurrentContext(ctx);
3515
0
    Shutdown();
3516
0
    SetCurrentContext((prev_ctx != ctx) ? prev_ctx : NULL);
3517
0
    IM_DELETE(ctx);
3518
0
}
3519
3520
// IMPORTANT: ###xxx suffixes must be same in ALL languages
3521
static const ImGuiLocEntry GLocalizationEntriesEnUS[] =
3522
{
3523
    { ImGuiLocKey_TableSizeOne,         "Size column to fit###SizeOne"          },
3524
    { ImGuiLocKey_TableSizeAllFit,      "Size all columns to fit###SizeAll"     },
3525
    { ImGuiLocKey_TableSizeAllDefault,  "Size all columns to default###SizeAll" },
3526
    { ImGuiLocKey_TableResetOrder,      "Reset order###ResetOrder"              },
3527
    { ImGuiLocKey_WindowingMainMenuBar, "(Main menu bar)"                       },
3528
    { ImGuiLocKey_WindowingPopup,       "(Popup)"                               },
3529
    { ImGuiLocKey_WindowingUntitled,    "(Untitled)"                            },
3530
    { ImGuiLocKey_DockingHideTabBar,    "Hide tab bar###HideTabBar"             },
3531
};
3532
3533
void ImGui::Initialize()
3534
1
{
3535
1
    ImGuiContext& g = *GImGui;
3536
1
    IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
3537
3538
    // Add .ini handle for ImGuiWindow and ImGuiTable types
3539
1
    {
3540
1
        ImGuiSettingsHandler ini_handler;
3541
1
        ini_handler.TypeName = "Window";
3542
1
        ini_handler.TypeHash = ImHashStr("Window");
3543
1
        ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;
3544
1
        ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
3545
1
        ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
3546
1
        ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll;
3547
1
        ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
3548
1
        AddSettingsHandler(&ini_handler);
3549
1
    }
3550
1
    TableSettingsAddSettingsHandler();
3551
3552
    // Setup default localization table
3553
1
    LocalizeRegisterEntries(GLocalizationEntriesEnUS, IM_ARRAYSIZE(GLocalizationEntriesEnUS));
3554
3555
    // Create default viewport
3556
1
    ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
3557
1
    viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID;
3558
1
    viewport->Idx = 0;
3559
1
    viewport->PlatformWindowCreated = true;
3560
1
    viewport->Flags = ImGuiViewportFlags_OwnedByApp;
3561
1
    g.Viewports.push_back(viewport);
3562
1
    g.TempBuffer.resize(1024 * 3 + 1, 0);
3563
1
    g.PlatformIO.Viewports.push_back(g.Viewports[0]);
3564
3565
1
#ifdef IMGUI_HAS_DOCK
3566
    // Initialize Docking
3567
1
    DockContextInitialize(&g);
3568
1
#endif
3569
3570
1
    g.Initialized = true;
3571
1
}
3572
3573
// This function is merely here to free heap allocations.
3574
void ImGui::Shutdown()
3575
0
{
3576
    // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame)
3577
0
    ImGuiContext& g = *GImGui;
3578
0
    if (g.IO.Fonts && g.FontAtlasOwnedByContext)
3579
0
    {
3580
0
        g.IO.Fonts->Locked = false;
3581
0
        IM_DELETE(g.IO.Fonts);
3582
0
    }
3583
0
    g.IO.Fonts = NULL;
3584
0
    g.DrawListSharedData.TempBuffer.clear();
3585
3586
    // Cleanup of other data are conditional on actually having initialized Dear ImGui.
3587
0
    if (!g.Initialized)
3588
0
        return;
3589
3590
    // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
3591
0
    if (g.SettingsLoaded && g.IO.IniFilename != NULL)
3592
0
        SaveIniSettingsToDisk(g.IO.IniFilename);
3593
3594
    // Destroy platform windows
3595
0
    DestroyPlatformWindows();
3596
3597
    // Shutdown extensions
3598
0
    DockContextShutdown(&g);
3599
3600
0
    CallContextHooks(&g, ImGuiContextHookType_Shutdown);
3601
3602
    // Clear everything else
3603
0
    g.Windows.clear_delete();
3604
0
    g.WindowsFocusOrder.clear();
3605
0
    g.WindowsTempSortBuffer.clear();
3606
0
    g.CurrentWindow = NULL;
3607
0
    g.CurrentWindowStack.clear();
3608
0
    g.WindowsById.Clear();
3609
0
    g.NavWindow = NULL;
3610
0
    g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
3611
0
    g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
3612
0
    g.MovingWindow = NULL;
3613
3614
0
    g.KeysRoutingTable.Clear();
3615
3616
0
    g.ColorStack.clear();
3617
0
    g.StyleVarStack.clear();
3618
0
    g.FontStack.clear();
3619
0
    g.OpenPopupStack.clear();
3620
0
    g.BeginPopupStack.clear();
3621
3622
0
    g.CurrentViewport = g.MouseViewport = g.MouseLastHoveredViewport = NULL;
3623
0
    g.Viewports.clear_delete();
3624
3625
0
    g.TabBars.Clear();
3626
0
    g.CurrentTabBarStack.clear();
3627
0
    g.ShrinkWidthBuffer.clear();
3628
3629
0
    g.ClipperTempData.clear_destruct();
3630
3631
0
    g.Tables.Clear();
3632
0
    g.TablesTempData.clear_destruct();
3633
0
    g.DrawChannelsTempMergeBuffer.clear();
3634
3635
0
    g.ClipboardHandlerData.clear();
3636
0
    g.MenusIdSubmittedThisFrame.clear();
3637
0
    g.InputTextState.ClearFreeMemory();
3638
3639
0
    g.SettingsWindows.clear();
3640
0
    g.SettingsHandlers.clear();
3641
3642
0
    if (g.LogFile)
3643
0
    {
3644
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
3645
0
        if (g.LogFile != stdout)
3646
0
#endif
3647
0
            ImFileClose(g.LogFile);
3648
0
        g.LogFile = NULL;
3649
0
    }
3650
0
    g.LogBuffer.clear();
3651
0
    g.DebugLogBuf.clear();
3652
0
    g.DebugLogIndex.clear();
3653
3654
0
    g.Initialized = false;
3655
0
}
3656
3657
// No specific ordering/dependency support, will see as needed
3658
ImGuiID ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook)
3659
0
{
3660
0
    ImGuiContext& g = *ctx;
3661
0
    IM_ASSERT(hook->Callback != NULL && hook->HookId == 0 && hook->Type != ImGuiContextHookType_PendingRemoval_);
3662
0
    g.Hooks.push_back(*hook);
3663
0
    g.Hooks.back().HookId = ++g.HookIdNext;
3664
0
    return g.HookIdNext;
3665
0
}
3666
3667
// Deferred removal, avoiding issue with changing vector while iterating it
3668
void ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id)
3669
0
{
3670
0
    ImGuiContext& g = *ctx;
3671
0
    IM_ASSERT(hook_id != 0);
3672
0
    for (int n = 0; n < g.Hooks.Size; n++)
3673
0
        if (g.Hooks[n].HookId == hook_id)
3674
0
            g.Hooks[n].Type = ImGuiContextHookType_PendingRemoval_;
3675
0
}
3676
3677
// Call context hooks (used by e.g. test engine)
3678
// We assume a small number of hooks so all stored in same array
3679
void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type)
3680
18.0k
{
3681
18.0k
    ImGuiContext& g = *ctx;
3682
18.0k
    for (int n = 0; n < g.Hooks.Size; n++)
3683
0
        if (g.Hooks[n].Type == hook_type)
3684
0
            g.Hooks[n].Callback(&g, &g.Hooks[n]);
3685
18.0k
}
3686
3687
3688
//-----------------------------------------------------------------------------
3689
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
3690
//-----------------------------------------------------------------------------
3691
3692
// ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
3693
ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name) : DrawListInst(NULL)
3694
3
{
3695
3
    memset(this, 0, sizeof(*this));
3696
3
    Name = ImStrdup(name);
3697
3
    NameBufLen = (int)strlen(name) + 1;
3698
3
    ID = ImHashStr(name);
3699
3
    IDStack.push_back(ID);
3700
3
    ViewportAllowPlatformMonitorExtend = -1;
3701
3
    ViewportPos = ImVec2(FLT_MAX, FLT_MAX);
3702
3
    MoveId = GetID("#MOVE");
3703
3
    TabId = GetID("#TAB");
3704
3
    ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
3705
3
    ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
3706
3
    AutoFitFramesX = AutoFitFramesY = -1;
3707
3
    AutoPosLastDirection = ImGuiDir_None;
3708
3
    SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = SetWindowDockAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
3709
3
    SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
3710
3
    LastFrameActive = -1;
3711
3
    LastFrameJustFocused = -1;
3712
3
    LastTimeActive = -1.0f;
3713
3
    FontWindowScale = FontDpiScale = 1.0f;
3714
3
    SettingsOffset = -1;
3715
3
    DockOrder = -1;
3716
3
    DrawList = &DrawListInst;
3717
3
    DrawList->_Data = &context->DrawListSharedData;
3718
3
    DrawList->_OwnerName = Name;
3719
3
    IM_PLACEMENT_NEW(&WindowClass) ImGuiWindowClass();
3720
3
}
3721
3722
ImGuiWindow::~ImGuiWindow()
3723
0
{
3724
0
    IM_ASSERT(DrawList == &DrawListInst);
3725
0
    IM_DELETE(Name);
3726
0
    ColumnsStorage.clear_destruct();
3727
0
}
3728
3729
ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
3730
18.1k
{
3731
18.1k
    ImGuiID seed = IDStack.back();
3732
18.1k
    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
3733
18.1k
    ImGuiContext& g = *GImGui;
3734
18.1k
    if (g.DebugHookIdInfo == id)
3735
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
3736
18.1k
    return id;
3737
18.1k
}
3738
3739
ImGuiID ImGuiWindow::GetID(const void* ptr)
3740
0
{
3741
0
    ImGuiID seed = IDStack.back();
3742
0
    ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
3743
0
    ImGuiContext& g = *GImGui;
3744
0
    if (g.DebugHookIdInfo == id)
3745
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_Pointer, ptr, NULL);
3746
0
    return id;
3747
0
}
3748
3749
ImGuiID ImGuiWindow::GetID(int n)
3750
3.00k
{
3751
3.00k
    ImGuiID seed = IDStack.back();
3752
3.00k
    ImGuiID id = ImHashData(&n, sizeof(n), seed);
3753
3.00k
    ImGuiContext& g = *GImGui;
3754
3.00k
    if (g.DebugHookIdInfo == id)
3755
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
3756
3.00k
    return id;
3757
3.00k
}
3758
3759
// This is only used in rare/specific situations to manufacture an ID out of nowhere.
3760
ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
3761
0
{
3762
0
    ImGuiID seed = IDStack.back();
3763
0
    ImRect r_rel = ImGui::WindowRectAbsToRel(this, r_abs);
3764
0
    ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);
3765
0
    return id;
3766
0
}
3767
3768
static void SetCurrentWindow(ImGuiWindow* window)
3769
18.0k
{
3770
18.0k
    ImGuiContext& g = *GImGui;
3771
18.0k
    g.CurrentWindow = window;
3772
18.0k
    g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL;
3773
18.0k
    if (window)
3774
15.0k
        g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
3775
18.0k
}
3776
3777
void ImGui::GcCompactTransientMiscBuffers()
3778
0
{
3779
0
    ImGuiContext& g = *GImGui;
3780
0
    g.ItemFlagsStack.clear();
3781
0
    g.GroupStack.clear();
3782
0
    TableGcCompactSettings();
3783
0
}
3784
3785
// Free up/compact internal window buffers, we can use this when a window becomes unused.
3786
// Not freed:
3787
// - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data)
3788
// This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
3789
void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
3790
0
{
3791
0
    window->MemoryCompacted = true;
3792
0
    window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
3793
0
    window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
3794
0
    window->IDStack.clear();
3795
0
    window->DrawList->_ClearFreeMemory();
3796
0
    window->DC.ChildWindows.clear();
3797
0
    window->DC.ItemWidthStack.clear();
3798
0
    window->DC.TextWrapPosStack.clear();
3799
0
}
3800
3801
void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
3802
0
{
3803
    // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
3804
    // The other buffers tends to amortize much faster.
3805
0
    window->MemoryCompacted = false;
3806
0
    window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity);
3807
0
    window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity);
3808
0
    window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
3809
0
}
3810
3811
void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
3812
0
{
3813
0
    ImGuiContext& g = *GImGui;
3814
3815
    // While most behaved code would make an effort to not steal active id during window move/drag operations,
3816
    // we at least need to be resilient to it. Cancelling the move is rather aggressive and users of 'master' branch
3817
    // may prefer the weird ill-defined half working situation ('docking' did assert), so may need to rework that.
3818
0
    if (g.MovingWindow != NULL && g.ActiveId == g.MovingWindow->MoveId)
3819
0
    {
3820
0
        IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() cancel MovingWindow\n");
3821
0
        g.MovingWindow = NULL;
3822
0
    }
3823
3824
    // Set active id
3825
0
    g.ActiveIdIsJustActivated = (g.ActiveId != id);
3826
0
    if (g.ActiveIdIsJustActivated)
3827
0
    {
3828
0
        IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() old:0x%08X (window \"%s\") -> new:0x%08X (window \"%s\")\n", g.ActiveId, g.ActiveIdWindow ? g.ActiveIdWindow->Name : "", id, window ? window->Name : "");
3829
0
        g.ActiveIdTimer = 0.0f;
3830
0
        g.ActiveIdHasBeenPressedBefore = false;
3831
0
        g.ActiveIdHasBeenEditedBefore = false;
3832
0
        g.ActiveIdMouseButton = -1;
3833
0
        if (id != 0)
3834
0
        {
3835
0
            g.LastActiveId = id;
3836
0
            g.LastActiveIdTimer = 0.0f;
3837
0
        }
3838
0
    }
3839
0
    g.ActiveId = id;
3840
0
    g.ActiveIdAllowOverlap = false;
3841
0
    g.ActiveIdNoClearOnFocusLoss = false;
3842
0
    g.ActiveIdWindow = window;
3843
0
    g.ActiveIdHasBeenEditedThisFrame = false;
3844
0
    if (id)
3845
0
    {
3846
0
        g.ActiveIdIsAlive = id;
3847
0
        g.ActiveIdSource = (g.NavActivateId == id || g.NavActivateInputId == id || g.NavJustMovedToId == id) ? (ImGuiInputSource)ImGuiInputSource_Nav : ImGuiInputSource_Mouse;
3848
0
    }
3849
3850
    // Clear declaration of inputs claimed by the widget
3851
    // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
3852
0
    g.ActiveIdUsingNavDirMask = 0x00;
3853
0
    g.ActiveIdUsingAllKeyboardKeys = false;
3854
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
3855
    g.ActiveIdUsingNavInputMask = 0x00;
3856
#endif
3857
0
}
3858
3859
void ImGui::ClearActiveID()
3860
0
{
3861
0
    SetActiveID(0, NULL); // g.ActiveId = 0;
3862
0
}
3863
3864
void ImGui::SetHoveredID(ImGuiID id)
3865
0
{
3866
0
    ImGuiContext& g = *GImGui;
3867
0
    g.HoveredId = id;
3868
0
    g.HoveredIdAllowOverlap = false;
3869
0
    if (id != 0 && g.HoveredIdPreviousFrame != id)
3870
0
        g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
3871
0
}
3872
3873
ImGuiID ImGui::GetHoveredID()
3874
0
{
3875
0
    ImGuiContext& g = *GImGui;
3876
0
    return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
3877
0
}
3878
3879
// This is called by ItemAdd().
3880
// Code not using ItemAdd() may need to call this manually otherwise ActiveId will be cleared. In IMGUI_VERSION_NUM < 18717 this was called by GetID().
3881
void ImGui::KeepAliveID(ImGuiID id)
3882
15.2k
{
3883
15.2k
    ImGuiContext& g = *GImGui;
3884
15.2k
    if (g.ActiveId == id)
3885
0
        g.ActiveIdIsAlive = id;
3886
15.2k
    if (g.ActiveIdPreviousFrame == id)
3887
0
        g.ActiveIdPreviousFrameIsAlive = true;
3888
15.2k
}
3889
3890
void ImGui::MarkItemEdited(ImGuiID id)
3891
0
{
3892
    // This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
3893
    // ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need to fill the data.
3894
0
    ImGuiContext& g = *GImGui;
3895
0
    IM_ASSERT(g.ActiveId == id || g.ActiveId == 0 || g.DragDropActive);
3896
0
    IM_UNUSED(id); // Avoid unused variable warnings when asserts are compiled out.
3897
    //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
3898
0
    g.ActiveIdHasBeenEditedThisFrame = true;
3899
0
    g.ActiveIdHasBeenEditedBefore = true;
3900
0
    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
3901
0
}
3902
3903
static inline bool IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
3904
0
{
3905
    // An active popup disable hovering on other windows (apart from its own children)
3906
    // FIXME-OPT: This could be cached/stored within the window.
3907
0
    ImGuiContext& g = *GImGui;
3908
0
    if (g.NavWindow)
3909
0
        if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindowDockTree)
3910
0
            if (focused_root_window->WasActive && focused_root_window != window->RootWindowDockTree)
3911
0
            {
3912
                // For the purpose of those flags we differentiate "standard popup" from "modal popup"
3913
                // NB: The 'else' is important because Modal windows are also Popups.
3914
0
                bool want_inhibit = false;
3915
0
                if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
3916
0
                    want_inhibit = true;
3917
0
                else if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
3918
0
                    want_inhibit = true;
3919
3920
                // Inhibit hover unless the window is within the stack of our modal/popup
3921
0
                if (want_inhibit)
3922
0
                    if (!ImGui::IsWindowWithinBeginStackOf(window->RootWindow, focused_root_window))
3923
0
                        return false;
3924
0
            }
3925
3926
    // Filter by viewport
3927
0
    if (window->Viewport != g.MouseViewport)
3928
0
        if (g.MovingWindow == NULL || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree)
3929
0
            return false;
3930
3931
0
    return true;
3932
0
}
3933
3934
// This is roughly matching the behavior of internal-facing ItemHoverable()
3935
// - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered()
3936
// - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
3937
bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
3938
0
{
3939
0
    ImGuiContext& g = *GImGui;
3940
0
    ImGuiWindow* window = g.CurrentWindow;
3941
0
    if (g.NavDisableMouseHover && !g.NavDisableHighlight && !(flags & ImGuiHoveredFlags_NoNavOverride))
3942
0
    {
3943
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
3944
0
            return false;
3945
0
        if (!IsItemFocused())
3946
0
            return false;
3947
0
    }
3948
0
    else
3949
0
    {
3950
        // Test for bounding box overlap, as updated as ItemAdd()
3951
0
        ImGuiItemStatusFlags status_flags = g.LastItemData.StatusFlags;
3952
0
        if (!(status_flags & ImGuiItemStatusFlags_HoveredRect))
3953
0
            return false;
3954
0
        IM_ASSERT((flags & (ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_NoPopupHierarchy | ImGuiHoveredFlags_DockHierarchy)) == 0);   // Flags not supported by this function
3955
3956
        // Done with rectangle culling so we can perform heavier checks now
3957
        // Test if we are hovering the right window (our window could be behind another window)
3958
        // [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851)
3959
        // [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable
3960
        // to use IsItemHovered() after EndChild() itself. Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was
3961
        // the test that has been running for a long while.
3962
0
        if (g.HoveredWindow != window && (status_flags & ImGuiItemStatusFlags_HoveredWindow) == 0)
3963
0
            if ((flags & ImGuiHoveredFlags_AllowWhenOverlapped) == 0)
3964
0
                return false;
3965
3966
        // Test if another item is active (e.g. being dragged)
3967
0
        if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0)
3968
0
            if (g.ActiveId != 0 && g.ActiveId != g.LastItemData.ID && !g.ActiveIdAllowOverlap)
3969
0
                if (g.ActiveId != window->MoveId && g.ActiveId != window->TabId)
3970
0
                    return false;
3971
3972
        // Test if interactions on this window are blocked by an active popup or modal.
3973
        // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
3974
0
        if (!IsWindowContentHoverable(window, flags) && !(g.LastItemData.InFlags & ImGuiItemFlags_NoWindowHoverableCheck))
3975
0
            return false;
3976
3977
        // Test if the item is disabled
3978
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
3979
0
            return false;
3980
3981
        // Special handling for calling after Begin() which represent the title bar or tab.
3982
        // When the window is skipped/collapsed (SkipItems==true) that last item (always ->MoveId submitted by Begin)
3983
        // will never be overwritten so we need to detect the case.
3984
0
        if (g.LastItemData.ID == window->MoveId && window->WriteAccessed)
3985
0
            return false;
3986
0
    }
3987
3988
    // Handle hover delay
3989
    // (some ideas: https://www.nngroup.com/articles/timing-exposing-content)
3990
0
    float delay;
3991
0
    if (flags & ImGuiHoveredFlags_DelayNormal)
3992
0
        delay = g.IO.HoverDelayNormal;
3993
0
    else if (flags & ImGuiHoveredFlags_DelayShort)
3994
0
        delay = g.IO.HoverDelayShort;
3995
0
    else
3996
0
        delay = 0.0f;
3997
0
    if (delay > 0.0f)
3998
0
    {
3999
0
        ImGuiID hover_delay_id = (g.LastItemData.ID != 0) ? g.LastItemData.ID : window->GetIDFromRectangle(g.LastItemData.Rect);
4000
0
        if ((flags & ImGuiHoveredFlags_NoSharedDelay) && (g.HoverDelayIdPreviousFrame != hover_delay_id))
4001
0
            g.HoverDelayTimer = 0.0f;
4002
0
        g.HoverDelayId = hover_delay_id;
4003
0
        return g.HoverDelayTimer >= delay;
4004
0
    }
4005
4006
0
    return true;
4007
0
}
4008
4009
// Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
4010
bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id)
4011
12.2k
{
4012
12.2k
    ImGuiContext& g = *GImGui;
4013
12.2k
    if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
4014
0
        return false;
4015
4016
12.2k
    ImGuiWindow* window = g.CurrentWindow;
4017
12.2k
    if (g.HoveredWindow != window)
4018
12.2k
        return false;
4019
0
    if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4020
0
        return false;
4021
0
    if (!IsMouseHoveringRect(bb.Min, bb.Max))
4022
0
        return false;
4023
4024
    // Done with rectangle culling so we can perform heavier checks now.
4025
0
    ImGuiItemFlags item_flags = (g.LastItemData.ID == id ? g.LastItemData.InFlags : g.CurrentItemFlags);
4026
0
    if (!(item_flags & ImGuiItemFlags_NoWindowHoverableCheck) && !IsWindowContentHoverable(window, ImGuiHoveredFlags_None))
4027
0
    {
4028
0
        g.HoveredIdDisabled = true;
4029
0
        return false;
4030
0
    }
4031
4032
    // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level
4033
    // hover test in widgets code. We could also decide to split this function is two.
4034
0
    if (id != 0)
4035
0
        SetHoveredID(id);
4036
4037
    // When disabled we'll return false but still set HoveredId
4038
0
    if (item_flags & ImGuiItemFlags_Disabled)
4039
0
    {
4040
        // Release active id if turning disabled
4041
0
        if (g.ActiveId == id)
4042
0
            ClearActiveID();
4043
0
        g.HoveredIdDisabled = true;
4044
0
        return false;
4045
0
    }
4046
4047
0
    if (id != 0)
4048
0
    {
4049
        // [DEBUG] Item Picker tool!
4050
        // We perform the check here because SetHoveredID() is not frequently called (1~ time a frame), making
4051
        // the cost of this tool near-zero. We can get slightly better call-stack and support picking non-hovered
4052
        // items if we performed the test in ItemAdd(), but that would incur a small runtime cost.
4053
0
        if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
4054
0
            GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
4055
0
        if (g.DebugItemPickerBreakId == id)
4056
0
            IM_DEBUG_BREAK();
4057
0
    }
4058
4059
0
    if (g.NavDisableMouseHover)
4060
0
        return false;
4061
4062
0
    return true;
4063
0
}
4064
4065
// FIXME: This is inlined/duplicated in ItemAdd()
4066
bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id)
4067
0
{
4068
0
    ImGuiContext& g = *GImGui;
4069
0
    ImGuiWindow* window = g.CurrentWindow;
4070
0
    if (!bb.Overlaps(window->ClipRect))
4071
0
        if (id == 0 || (id != g.ActiveId && id != g.NavId))
4072
0
            if (!g.LogEnabled)
4073
0
                return true;
4074
0
    return false;
4075
0
}
4076
4077
// This is also inlined in ItemAdd()
4078
// Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set window->DC.LastItemDisplayRect!
4079
void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags in_flags, ImGuiItemStatusFlags item_flags, const ImRect& item_rect)
4080
9.00k
{
4081
9.00k
    ImGuiContext& g = *GImGui;
4082
9.00k
    g.LastItemData.ID = item_id;
4083
9.00k
    g.LastItemData.InFlags = in_flags;
4084
9.00k
    g.LastItemData.StatusFlags = item_flags;
4085
9.00k
    g.LastItemData.Rect = item_rect;
4086
9.00k
}
4087
4088
float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
4089
0
{
4090
0
    if (wrap_pos_x < 0.0f)
4091
0
        return 0.0f;
4092
4093
0
    ImGuiContext& g = *GImGui;
4094
0
    ImGuiWindow* window = g.CurrentWindow;
4095
0
    if (wrap_pos_x == 0.0f)
4096
0
    {
4097
        // We could decide to setup a default wrapping max point for auto-resizing windows,
4098
        // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function?
4099
        //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize))
4100
        //    wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x);
4101
        //else
4102
0
        wrap_pos_x = window->WorkRect.Max.x;
4103
0
    }
4104
0
    else if (wrap_pos_x > 0.0f)
4105
0
    {
4106
0
        wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
4107
0
    }
4108
4109
0
    return ImMax(wrap_pos_x - pos.x, 1.0f);
4110
0
}
4111
4112
// IM_ALLOC() == ImGui::MemAlloc()
4113
void* ImGui::MemAlloc(size_t size)
4114
1.20k
{
4115
1.20k
    if (ImGuiContext* ctx = GImGui)
4116
1.20k
        ctx->IO.MetricsActiveAllocations++;
4117
1.20k
    return (*GImAllocatorAllocFunc)(size, GImAllocatorUserData);
4118
1.20k
}
4119
4120
// IM_FREE() == ImGui::MemFree()
4121
void ImGui::MemFree(void* ptr)
4122
1.15k
{
4123
1.15k
    if (ptr)
4124
1.14k
        if (ImGuiContext* ctx = GImGui)
4125
1.14k
            ctx->IO.MetricsActiveAllocations--;
4126
1.15k
    return (*GImAllocatorFreeFunc)(ptr, GImAllocatorUserData);
4127
1.15k
}
4128
4129
const char* ImGui::GetClipboardText()
4130
0
{
4131
0
    ImGuiContext& g = *GImGui;
4132
0
    return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : "";
4133
0
}
4134
4135
void ImGui::SetClipboardText(const char* text)
4136
0
{
4137
0
    ImGuiContext& g = *GImGui;
4138
0
    if (g.IO.SetClipboardTextFn)
4139
0
        g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text);
4140
0
}
4141
4142
const char* ImGui::GetVersion()
4143
0
{
4144
0
    return IMGUI_VERSION;
4145
0
}
4146
4147
ImGuiIO& ImGui::GetIO()
4148
13.2k
{
4149
13.2k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4150
13.2k
    return GImGui->IO;
4151
13.2k
}
4152
4153
ImGuiPlatformIO& ImGui::GetPlatformIO()
4154
0
{
4155
0
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
4156
0
    return GImGui->PlatformIO;
4157
0
}
4158
4159
// Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame()
4160
ImDrawData* ImGui::GetDrawData()
4161
3.00k
{
4162
3.00k
    ImGuiContext& g = *GImGui;
4163
3.00k
    ImGuiViewportP* viewport = g.Viewports[0];
4164
3.00k
    return viewport->DrawDataP.Valid ? &viewport->DrawDataP : NULL;
4165
3.00k
}
4166
4167
double ImGui::GetTime()
4168
0
{
4169
0
    return GImGui->Time;
4170
0
}
4171
4172
int ImGui::GetFrameCount()
4173
0
{
4174
0
    return GImGui->FrameCount;
4175
0
}
4176
4177
static ImDrawList* GetViewportDrawList(ImGuiViewportP* viewport, size_t drawlist_no, const char* drawlist_name)
4178
0
{
4179
    // Create the draw list on demand, because they are not frequently used for all viewports
4180
0
    ImGuiContext& g = *GImGui;
4181
0
    IM_ASSERT(drawlist_no < IM_ARRAYSIZE(viewport->DrawLists));
4182
0
    ImDrawList* draw_list = viewport->DrawLists[drawlist_no];
4183
0
    if (draw_list == NULL)
4184
0
    {
4185
0
        draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData);
4186
0
        draw_list->_OwnerName = drawlist_name;
4187
0
        viewport->DrawLists[drawlist_no] = draw_list;
4188
0
    }
4189
4190
    // Our ImDrawList system requires that there is always a command
4191
0
    if (viewport->DrawListsLastFrame[drawlist_no] != g.FrameCount)
4192
0
    {
4193
0
        draw_list->_ResetForNewFrame();
4194
0
        draw_list->PushTextureID(g.IO.Fonts->TexID);
4195
0
        draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false);
4196
0
        viewport->DrawListsLastFrame[drawlist_no] = g.FrameCount;
4197
0
    }
4198
0
    return draw_list;
4199
0
}
4200
4201
ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport)
4202
0
{
4203
0
    return GetViewportDrawList((ImGuiViewportP*)viewport, 0, "##Background");
4204
0
}
4205
4206
ImDrawList* ImGui::GetBackgroundDrawList()
4207
0
{
4208
0
    ImGuiContext& g = *GImGui;
4209
0
    return GetBackgroundDrawList(g.CurrentWindow->Viewport);
4210
0
}
4211
4212
ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport)
4213
0
{
4214
0
    return GetViewportDrawList((ImGuiViewportP*)viewport, 1, "##Foreground");
4215
0
}
4216
4217
ImDrawList* ImGui::GetForegroundDrawList()
4218
0
{
4219
0
    ImGuiContext& g = *GImGui;
4220
0
    return GetForegroundDrawList(g.CurrentWindow->Viewport);
4221
0
}
4222
4223
ImDrawListSharedData* ImGui::GetDrawListSharedData()
4224
0
{
4225
0
    return &GImGui->DrawListSharedData;
4226
0
}
4227
4228
void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
4229
0
{
4230
    // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
4231
    // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
4232
    // This is because we want ActiveId to be set even when the window is not permitted to move.
4233
0
    ImGuiContext& g = *GImGui;
4234
0
    FocusWindow(window);
4235
0
    SetActiveID(window->MoveId, window);
4236
0
    g.NavDisableHighlight = true;
4237
0
    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindowDockTree->Pos;
4238
0
    g.ActiveIdNoClearOnFocusLoss = true;
4239
0
    SetActiveIdUsingAllKeyboardKeys();
4240
4241
0
    bool can_move_window = true;
4242
0
    if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoMove))
4243
0
        can_move_window = false;
4244
0
    if (ImGuiDockNode* node = window->DockNodeAsHost)
4245
0
        if (node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove))
4246
0
            can_move_window = false;
4247
0
    if (can_move_window)
4248
0
        g.MovingWindow = window;
4249
0
}
4250
4251
// We use 'undock_floating_node == false' when dragging from title bar to allow moving groups of floating nodes without undocking them.
4252
// - undock_floating_node == true: when dragging from a floating node within a hierarchy, always undock the node.
4253
// - undock_floating_node == false: when dragging from a floating node within a hierarchy, move root window.
4254
void ImGui::StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* node, bool undock_floating_node)
4255
0
{
4256
0
    ImGuiContext& g = *GImGui;
4257
0
    bool can_undock_node = false;
4258
0
    if (node != NULL && node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove) == 0)
4259
0
    {
4260
        // Can undock if:
4261
        // - part of a floating node hierarchy with more than one visible node (if only one is visible, we'll just move the whole hierarchy)
4262
        // - part of a dockspace node hierarchy (trivia: undocking from a fixed/central node will create a new node and copy windows)
4263
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
4264
0
        if (root_node->OnlyNodeWithWindows != node || root_node->CentralNode != NULL)   // -V1051 PVS-Studio thinks node should be root_node and is wrong about that.
4265
0
            if (undock_floating_node || root_node->IsDockSpace())
4266
0
                can_undock_node = true;
4267
0
    }
4268
4269
0
    const bool clicked = IsMouseClicked(0);
4270
0
    const bool dragging = IsMouseDragging(0, g.IO.MouseDragThreshold * 1.70f);
4271
0
    if (can_undock_node && dragging)
4272
0
        DockContextQueueUndockNode(&g, node); // Will lead to DockNodeStartMouseMovingWindow() -> StartMouseMovingWindow() being called next frame
4273
0
    else if (!can_undock_node && (clicked || dragging) && g.MovingWindow != window)
4274
0
        StartMouseMovingWindow(window);
4275
0
}
4276
4277
// Handle mouse moving window
4278
// Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
4279
// FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId.
4280
// This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
4281
// but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.
4282
void ImGui::UpdateMouseMovingWindowNewFrame()
4283
3.00k
{
4284
3.00k
    ImGuiContext& g = *GImGui;
4285
3.00k
    if (g.MovingWindow != NULL)
4286
0
    {
4287
        // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
4288
        // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
4289
0
        KeepAliveID(g.ActiveId);
4290
0
        IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindowDockTree);
4291
0
        ImGuiWindow* moving_window = g.MovingWindow->RootWindowDockTree;
4292
4293
        // When a window stop being submitted while being dragged, it may will its viewport until next Begin()
4294
0
        const bool window_disappared = ((!moving_window->WasActive && !moving_window->Active) || moving_window->Viewport == NULL);
4295
0
        if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos) && !window_disappared)
4296
0
        {
4297
0
            ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
4298
0
            if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
4299
0
            {
4300
0
                SetWindowPos(moving_window, pos, ImGuiCond_Always);
4301
0
                if (moving_window->ViewportOwned) // Synchronize viewport immediately because some overlays may relies on clipping rectangle before we Begin() into the window.
4302
0
                {
4303
0
                    moving_window->Viewport->Pos = pos;
4304
0
                    moving_window->Viewport->UpdateWorkRect();
4305
0
                }
4306
0
            }
4307
0
            FocusWindow(g.MovingWindow);
4308
0
        }
4309
0
        else
4310
0
        {
4311
0
            if (!window_disappared)
4312
0
            {
4313
                // Try to merge the window back into the main viewport.
4314
                // This works because MouseViewport should be != MovingWindow->Viewport on release (as per code in UpdateViewports)
4315
0
                if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
4316
0
                    UpdateTryMergeWindowIntoHostViewport(moving_window, g.MouseViewport);
4317
4318
                // Restore the mouse viewport so that we don't hover the viewport _under_ the moved window during the frame we released the mouse button.
4319
0
                if (!IsDragDropPayloadBeingAccepted())
4320
0
                    g.MouseViewport = moving_window->Viewport;
4321
4322
                // Clear the NoInput window flag set by the Viewport system
4323
0
                moving_window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs; // FIXME-VIEWPORT: Test engine managed to crash here because Viewport was NULL.
4324
0
            }
4325
4326
0
            g.MovingWindow = NULL;
4327
0
            ClearActiveID();
4328
0
        }
4329
0
    }
4330
3.00k
    else
4331
3.00k
    {
4332
        // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
4333
3.00k
        if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
4334
0
        {
4335
0
            KeepAliveID(g.ActiveId);
4336
0
            if (!g.IO.MouseDown[0])
4337
0
                ClearActiveID();
4338
0
        }
4339
3.00k
    }
4340
3.00k
}
4341
4342
// Initiate moving window when clicking on empty space or title bar.
4343
// Handle left-click and right-click focus.
4344
void ImGui::UpdateMouseMovingWindowEndFrame()
4345
3.00k
{
4346
3.00k
    ImGuiContext& g = *GImGui;
4347
3.00k
    if (g.ActiveId != 0 || g.HoveredId != 0)
4348
0
        return;
4349
4350
    // Unless we just made a window/popup appear
4351
3.00k
    if (g.NavWindow && g.NavWindow->Appearing)
4352
1
        return;
4353
4354
    // Click on empty space to focus window and start moving
4355
    // (after we're done with all our widgets, so e.g. clicking on docking tab-bar which have set HoveredId already and not get us here!)
4356
3.00k
    if (g.IO.MouseClicked[0])
4357
341
    {
4358
        // Handle the edge case of a popup being closed while clicking in its empty space.
4359
        // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more.
4360
341
        ImGuiWindow* root_window = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
4361
341
        const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(root_window->PopupId, ImGuiPopupFlags_AnyPopupLevel);
4362
4363
341
        if (root_window != NULL && !is_closed_popup)
4364
0
        {
4365
0
            StartMouseMovingWindow(g.HoveredWindow); //-V595
4366
4367
            // Cancel moving if clicked outside of title bar
4368
0
            if (g.IO.ConfigWindowsMoveFromTitleBarOnly)
4369
0
                if (!(root_window->Flags & ImGuiWindowFlags_NoTitleBar) || root_window->DockIsActive)
4370
0
                    if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
4371
0
                        g.MovingWindow = NULL;
4372
4373
            // Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already)
4374
0
            if (g.HoveredIdDisabled)
4375
0
                g.MovingWindow = NULL;
4376
0
        }
4377
341
        else if (root_window == NULL && g.NavWindow != NULL && GetTopMostPopupModal() == NULL)
4378
271
        {
4379
            // Clicking on void disable focus
4380
271
            FocusWindow(NULL);
4381
271
        }
4382
341
    }
4383
4384
    // With right mouse button we close popups without changing focus based on where the mouse is aimed
4385
    // Instead, focus will be restored to the window under the bottom-most closed popup.
4386
    // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
4387
3.00k
    if (g.IO.MouseClicked[1])
4388
12
    {
4389
        // Find the top-most window between HoveredWindow and the top-most Modal Window.
4390
        // This is where we can trim the popup stack.
4391
12
        ImGuiWindow* modal = GetTopMostPopupModal();
4392
12
        bool hovered_window_above_modal = g.HoveredWindow && (modal == NULL || IsWindowAbove(g.HoveredWindow, modal));
4393
12
        ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true);
4394
12
    }
4395
3.00k
}
4396
4397
// This is called during NewFrame()->UpdateViewportsNewFrame() only.
4398
// Need to keep in sync with SetWindowPos()
4399
static void TranslateWindow(ImGuiWindow* window, const ImVec2& delta)
4400
0
{
4401
0
    window->Pos += delta;
4402
0
    window->ClipRect.Translate(delta);
4403
0
    window->OuterRectClipped.Translate(delta);
4404
0
    window->InnerRect.Translate(delta);
4405
0
    window->DC.CursorPos += delta;
4406
0
    window->DC.CursorStartPos += delta;
4407
0
    window->DC.CursorMaxPos += delta;
4408
0
    window->DC.IdealMaxPos += delta;
4409
0
}
4410
4411
static void ScaleWindow(ImGuiWindow* window, float scale)
4412
0
{
4413
0
    ImVec2 origin = window->Viewport->Pos;
4414
0
    window->Pos = ImFloor((window->Pos - origin) * scale + origin);
4415
0
    window->Size = ImFloor(window->Size * scale);
4416
0
    window->SizeFull = ImFloor(window->SizeFull * scale);
4417
0
    window->ContentSize = ImFloor(window->ContentSize * scale);
4418
0
}
4419
4420
static bool IsWindowActiveAndVisible(ImGuiWindow* window)
4421
12.0k
{
4422
12.0k
    return (window->Active) && (!window->Hidden);
4423
12.0k
}
4424
4425
// The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app)
4426
void ImGui::UpdateHoveredWindowAndCaptureFlags()
4427
3.00k
{
4428
3.00k
    ImGuiContext& g = *GImGui;
4429
3.00k
    ImGuiIO& io = g.IO;
4430
3.00k
    g.WindowsHoverPadding = ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_HOVER_PADDING, WINDOWS_HOVER_PADDING));
4431
4432
    // Find the window hovered by mouse:
4433
    // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
4434
    // - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame.
4435
    // - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms.
4436
3.00k
    bool clear_hovered_windows = false;
4437
3.00k
    FindHoveredWindow();
4438
3.00k
    IM_ASSERT(g.HoveredWindow == NULL || g.HoveredWindow == g.MovingWindow || g.HoveredWindow->Viewport == g.MouseViewport);
4439
4440
    // Modal windows prevents mouse from hovering behind them.
4441
3.00k
    ImGuiWindow* modal_window = GetTopMostPopupModal();
4442
3.00k
    if (modal_window && g.HoveredWindow && !IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, modal_window)) // FIXME-MERGE: RootWindowDockTree ?
4443
0
        clear_hovered_windows = true;
4444
4445
    // Disabled mouse?
4446
3.00k
    if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)
4447
0
        clear_hovered_windows = true;
4448
4449
    // We track click ownership. When clicked outside of a window the click is owned by the application and
4450
    // won't report hovering nor request capture even while dragging over our windows afterward.
4451
3.00k
    const bool has_open_popup = (g.OpenPopupStack.Size > 0);
4452
3.00k
    const bool has_open_modal = (modal_window != NULL);
4453
3.00k
    int mouse_earliest_down = -1;
4454
3.00k
    bool mouse_any_down = false;
4455
18.0k
    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
4456
15.0k
    {
4457
15.0k
        if (io.MouseClicked[i])
4458
394
        {
4459
394
            io.MouseDownOwned[i] = (g.HoveredWindow != NULL) || has_open_popup;
4460
394
            io.MouseDownOwnedUnlessPopupClose[i] = (g.HoveredWindow != NULL) || has_open_modal;
4461
394
        }
4462
15.0k
        mouse_any_down |= io.MouseDown[i];
4463
15.0k
        if (io.MouseDown[i])
4464
2.05k
            if (mouse_earliest_down == -1 || io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down])
4465
1.79k
                mouse_earliest_down = i;
4466
15.0k
    }
4467
3.00k
    const bool mouse_avail = (mouse_earliest_down == -1) || io.MouseDownOwned[mouse_earliest_down];
4468
3.00k
    const bool mouse_avail_unless_popup_close = (mouse_earliest_down == -1) || io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down];
4469
4470
    // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
4471
    // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
4472
3.00k
    const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
4473
3.00k
    if (!mouse_avail && !mouse_dragging_extern_payload)
4474
1.19k
        clear_hovered_windows = true;
4475
4476
3.00k
    if (clear_hovered_windows)
4477
1.19k
        g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
4478
4479
    // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui only, false = dispatch mouse to Dear ImGui + underlying app)
4480
    // Update io.WantCaptureMouseAllowPopupClose (experimental) to give a chance for app to react to popup closure with a drag
4481
3.00k
    if (g.WantCaptureMouseNextFrame != -1)
4482
0
    {
4483
0
        io.WantCaptureMouse = io.WantCaptureMouseUnlessPopupClose = (g.WantCaptureMouseNextFrame != 0);
4484
0
    }
4485
3.00k
    else
4486
3.00k
    {
4487
3.00k
        io.WantCaptureMouse = (mouse_avail && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_popup;
4488
3.00k
        io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_modal;
4489
3.00k
    }
4490
4491
    // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app)
4492
3.00k
    if (g.WantCaptureKeyboardNextFrame != -1)
4493
0
        io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
4494
3.00k
    else
4495
3.00k
        io.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
4496
3.00k
    if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(io.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
4497
2.08k
        io.WantCaptureKeyboard = true;
4498
4499
    // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
4500
3.00k
    io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
4501
3.00k
}
4502
4503
void ImGui::NewFrame()
4504
3.00k
{
4505
3.00k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4506
3.00k
    ImGuiContext& g = *GImGui;
4507
4508
    // Remove pending delete hooks before frame start.
4509
    // This deferred removal avoid issues of removal while iterating the hook vector
4510
3.00k
    for (int n = g.Hooks.Size - 1; n >= 0; n--)
4511
0
        if (g.Hooks[n].Type == ImGuiContextHookType_PendingRemoval_)
4512
0
            g.Hooks.erase(&g.Hooks[n]);
4513
4514
3.00k
    CallContextHooks(&g, ImGuiContextHookType_NewFramePre);
4515
4516
    // Check and assert for various common IO and Configuration mistakes
4517
3.00k
    g.ConfigFlagsLastFrame = g.ConfigFlagsCurrFrame;
4518
3.00k
    ErrorCheckNewFrameSanityChecks();
4519
3.00k
    g.ConfigFlagsCurrFrame = g.IO.ConfigFlags;
4520
4521
    // Load settings on first frame, save settings when modified (after a delay)
4522
3.00k
    UpdateSettings();
4523
4524
3.00k
    g.Time += g.IO.DeltaTime;
4525
3.00k
    g.WithinFrameScope = true;
4526
3.00k
    g.FrameCount += 1;
4527
3.00k
    g.TooltipOverrideCount = 0;
4528
3.00k
    g.WindowsActiveCount = 0;
4529
3.00k
    g.MenusIdSubmittedThisFrame.resize(0);
4530
4531
    // Calculate frame-rate for the user, as a purely luxurious feature
4532
3.00k
    g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
4533
3.00k
    g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
4534
3.00k
    g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
4535
3.00k
    g.FramerateSecPerFrameCount = ImMin(g.FramerateSecPerFrameCount + 1, IM_ARRAYSIZE(g.FramerateSecPerFrame));
4536
3.00k
    g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)g.FramerateSecPerFrameCount)) : FLT_MAX;
4537
4538
    // Process input queue (trickle as many events as possible), turn events into writes to IO structure
4539
3.00k
    g.InputEventsTrail.resize(0);
4540
3.00k
    UpdateInputEvents(g.IO.ConfigInputTrickleEventQueue);
4541
4542
    // Update viewports (after processing input queue, so io.MouseHoveredViewport is set)
4543
3.00k
    UpdateViewportsNewFrame();
4544
4545
    // Setup current font and draw list shared data
4546
    // FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal!
4547
3.00k
    g.IO.Fonts->Locked = true;
4548
3.00k
    SetCurrentFont(GetDefaultFont());
4549
3.00k
    IM_ASSERT(g.Font->IsLoaded());
4550
3.00k
    ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
4551
6.00k
    for (int n = 0; n < g.Viewports.Size; n++)
4552
3.00k
        virtual_space.Add(g.Viewports[n]->GetMainRect());
4553
3.00k
    g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4();
4554
3.00k
    g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
4555
3.00k
    g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError);
4556
3.00k
    g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
4557
3.00k
    if (g.Style.AntiAliasedLines)
4558
3.00k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
4559
3.00k
    if (g.Style.AntiAliasedLinesUseTex && !(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoBakedLines))
4560
3.00k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex;
4561
3.00k
    if (g.Style.AntiAliasedFill)
4562
3.00k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
4563
3.00k
    if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
4564
0
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
4565
4566
    // Mark rendering data as invalid to prevent user who may have a handle on it to use it.
4567
6.00k
    for (int n = 0; n < g.Viewports.Size; n++)
4568
3.00k
    {
4569
3.00k
        ImGuiViewportP* viewport = g.Viewports[n];
4570
3.00k
        viewport->DrawData = NULL;
4571
3.00k
        viewport->DrawDataP.Clear();
4572
3.00k
    }
4573
4574
    // Drag and drop keep the source ID alive so even if the source disappear our state is consistent
4575
3.00k
    if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
4576
0
        KeepAliveID(g.DragDropPayload.SourceId);
4577
4578
    // Update HoveredId data
4579
3.00k
    if (!g.HoveredIdPreviousFrame)
4580
3.00k
        g.HoveredIdTimer = 0.0f;
4581
3.00k
    if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
4582
3.00k
        g.HoveredIdNotActiveTimer = 0.0f;
4583
3.00k
    if (g.HoveredId)
4584
0
        g.HoveredIdTimer += g.IO.DeltaTime;
4585
3.00k
    if (g.HoveredId && g.ActiveId != g.HoveredId)
4586
0
        g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
4587
3.00k
    g.HoveredIdPreviousFrame = g.HoveredId;
4588
3.00k
    g.HoveredId = 0;
4589
3.00k
    g.HoveredIdAllowOverlap = false;
4590
3.00k
    g.HoveredIdDisabled = false;
4591
4592
    // Clear ActiveID if the item is not alive anymore.
4593
    // In 1.87, the common most call to KeepAliveID() was moved from GetID() to ItemAdd().
4594
    // As a result, custom widget using ButtonBehavior() _without_ ItemAdd() need to call KeepAliveID() themselves.
4595
3.00k
    if (g.ActiveId != 0 && g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId)
4596
0
    {
4597
0
        IMGUI_DEBUG_LOG_ACTIVEID("NewFrame(): ClearActiveID() because it isn't marked alive anymore!\n");
4598
0
        ClearActiveID();
4599
0
    }
4600
4601
    // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
4602
3.00k
    if (g.ActiveId)
4603
0
        g.ActiveIdTimer += g.IO.DeltaTime;
4604
3.00k
    g.LastActiveIdTimer += g.IO.DeltaTime;
4605
3.00k
    g.ActiveIdPreviousFrame = g.ActiveId;
4606
3.00k
    g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
4607
3.00k
    g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
4608
3.00k
    g.ActiveIdIsAlive = 0;
4609
3.00k
    g.ActiveIdHasBeenEditedThisFrame = false;
4610
3.00k
    g.ActiveIdPreviousFrameIsAlive = false;
4611
3.00k
    g.ActiveIdIsJustActivated = false;
4612
3.00k
    if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
4613
0
        g.TempInputId = 0;
4614
3.00k
    if (g.ActiveId == 0)
4615
3.00k
    {
4616
3.00k
        g.ActiveIdUsingNavDirMask = 0x00;
4617
3.00k
        g.ActiveIdUsingAllKeyboardKeys = false;
4618
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4619
        g.ActiveIdUsingNavInputMask = 0x00;
4620
#endif
4621
3.00k
    }
4622
4623
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4624
    if (g.ActiveId == 0)
4625
        g.ActiveIdUsingNavInputMask = 0;
4626
    else if (g.ActiveIdUsingNavInputMask != 0)
4627
    {
4628
        // If your custom widget code used:                 { g.ActiveIdUsingNavInputMask |= (1 << ImGuiNavInput_Cancel); }
4629
        // Since IMGUI_VERSION_NUM >= 18804 it should be:   { SetKeyOwner(ImGuiKey_Escape, g.ActiveId); SetKeyOwner(ImGuiKey_NavGamepadCancel, g.ActiveId); }
4630
        if (g.ActiveIdUsingNavInputMask & (1 << ImGuiNavInput_Cancel))
4631
            SetKeyOwner(ImGuiKey_Escape, g.ActiveId);
4632
        if (g.ActiveIdUsingNavInputMask & ~(1 << ImGuiNavInput_Cancel))
4633
            IM_ASSERT(0); // Other values unsupported
4634
    }
4635
#endif
4636
4637
    // Update hover delay for IsItemHovered() with delays and tooltips
4638
3.00k
    g.HoverDelayIdPreviousFrame = g.HoverDelayId;
4639
3.00k
    if (g.HoverDelayId != 0)
4640
0
    {
4641
        //if (g.IO.MouseDelta.x == 0.0f && g.IO.MouseDelta.y == 0.0f) // Need design/flags
4642
0
        g.HoverDelayTimer += g.IO.DeltaTime;
4643
0
        g.HoverDelayClearTimer = 0.0f;
4644
0
        g.HoverDelayId = 0;
4645
0
    }
4646
3.00k
    else if (g.HoverDelayTimer > 0.0f)
4647
0
    {
4648
        // This gives a little bit of leeway before clearing the hover timer, allowing mouse to cross gaps
4649
0
        g.HoverDelayClearTimer += g.IO.DeltaTime;
4650
0
        if (g.HoverDelayClearTimer >= ImMax(0.20f, g.IO.DeltaTime * 2.0f)) // ~6 frames at 30 Hz + allow for low framerate
4651
0
            g.HoverDelayTimer = g.HoverDelayClearTimer = 0.0f; // May want a decaying timer, in which case need to clamp at max first, based on max of caller last requested timer.
4652
0
    }
4653
4654
    // Drag and drop
4655
3.00k
    g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
4656
3.00k
    g.DragDropAcceptIdCurr = 0;
4657
3.00k
    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
4658
3.00k
    g.DragDropWithinSource = false;
4659
3.00k
    g.DragDropWithinTarget = false;
4660
3.00k
    g.DragDropHoldJustPressedId = 0;
4661
4662
    // Close popups on focus lost (currently wip/opt-in)
4663
    //if (g.IO.AppFocusLost)
4664
    //    ClosePopupsExceptModals();
4665
4666
    // Update keyboard input state
4667
3.00k
    UpdateKeyboardInputs();
4668
4669
    //IM_ASSERT(g.IO.KeyCtrl == IsKeyDown(ImGuiKey_LeftCtrl) || IsKeyDown(ImGuiKey_RightCtrl));
4670
    //IM_ASSERT(g.IO.KeyShift == IsKeyDown(ImGuiKey_LeftShift) || IsKeyDown(ImGuiKey_RightShift));
4671
    //IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt));
4672
    //IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper));
4673
4674
    // Update gamepad/keyboard navigation
4675
3.00k
    NavUpdate();
4676
4677
    // Update mouse input state
4678
3.00k
    UpdateMouseInputs();
4679
4680
    // Undocking
4681
    // (needs to be before UpdateMouseMovingWindowNewFrame so the window is already offset and following the mouse on the detaching frame)
4682
3.00k
    DockContextNewFrameUpdateUndocking(&g);
4683
4684
    // Find hovered window
4685
    // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
4686
3.00k
    UpdateHoveredWindowAndCaptureFlags();
4687
4688
    // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
4689
3.00k
    UpdateMouseMovingWindowNewFrame();
4690
4691
    // Background darkening/whitening
4692
3.00k
    if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
4693
0
        g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
4694
3.00k
    else
4695
3.00k
        g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
4696
4697
3.00k
    g.MouseCursor = ImGuiMouseCursor_Arrow;
4698
3.00k
    g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
4699
4700
    // Platform IME data: reset for the frame
4701
3.00k
    g.PlatformImeDataPrev = g.PlatformImeData;
4702
3.00k
    g.PlatformImeData.WantVisible = false;
4703
4704
    // Mouse wheel scrolling, scale
4705
3.00k
    UpdateMouseWheel();
4706
4707
    // Mark all windows as not visible and compact unused memory.
4708
3.00k
    IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size);
4709
3.00k
    const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;
4710
12.0k
    for (int i = 0; i != g.Windows.Size; i++)
4711
9.00k
    {
4712
9.00k
        ImGuiWindow* window = g.Windows[i];
4713
9.00k
        window->WasActive = window->Active;
4714
9.00k
        window->Active = false;
4715
9.00k
        window->WriteAccessed = false;
4716
9.00k
        window->BeginCountPreviousFrame = window->BeginCount;
4717
9.00k
        window->BeginCount = 0;
4718
4719
        // Garbage collect transient buffers of recently unused windows
4720
9.00k
        if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
4721
0
            GcCompactTransientWindowBuffers(window);
4722
9.00k
    }
4723
4724
    // Garbage collect transient buffers of recently unused tables
4725
3.00k
    for (int i = 0; i < g.TablesLastTimeActive.Size; i++)
4726
0
        if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time)
4727
0
            TableGcCompactTransientBuffers(g.Tables.GetByIndex(i));
4728
3.00k
    for (int i = 0; i < g.TablesTempData.Size; i++)
4729
0
        if (g.TablesTempData[i].LastTimeActive >= 0.0f && g.TablesTempData[i].LastTimeActive < memory_compact_start_time)
4730
0
            TableGcCompactTransientBuffers(&g.TablesTempData[i]);
4731
3.00k
    if (g.GcCompactAll)
4732
0
        GcCompactTransientMiscBuffers();
4733
3.00k
    g.GcCompactAll = false;
4734
4735
    // Closing the focused window restore focus to the first active root window in descending z-order
4736
3.00k
    if (g.NavWindow && !g.NavWindow->WasActive)
4737
0
        FocusTopMostWindowUnderOne(NULL, NULL);
4738
4739
    // No window should be open at the beginning of the frame.
4740
    // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
4741
3.00k
    g.CurrentWindowStack.resize(0);
4742
3.00k
    g.BeginPopupStack.resize(0);
4743
3.00k
    g.ItemFlagsStack.resize(0);
4744
3.00k
    g.ItemFlagsStack.push_back(ImGuiItemFlags_None);
4745
3.00k
    g.GroupStack.resize(0);
4746
4747
    // Docking
4748
3.00k
    DockContextNewFrameUpdateDocking(&g);
4749
4750
    // [DEBUG] Update debug features
4751
3.00k
    UpdateDebugToolItemPicker();
4752
3.00k
    UpdateDebugToolStackQueries();
4753
3.00k
    if (g.DebugLocateFrames > 0 && --g.DebugLocateFrames == 0)
4754
0
        g.DebugLocateId = 0;
4755
4756
    // Create implicit/fallback window - which we will only render it if the user has added something to it.
4757
    // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
4758
    // This fallback is particularly important as it prevents ImGui:: calls from crashing.
4759
3.00k
    g.WithinFrameScopeWithImplicitWindow = true;
4760
3.00k
    SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);
4761
3.00k
    Begin("Debug##Default");
4762
3.00k
    IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
4763
4764
3.00k
    CallContextHooks(&g, ImGuiContextHookType_NewFramePost);
4765
3.00k
}
4766
4767
// FIXME: Add a more explicit sort order in the window structure.
4768
static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
4769
0
{
4770
0
    const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
4771
0
    const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
4772
0
    if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
4773
0
        return d;
4774
0
    if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
4775
0
        return d;
4776
0
    return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
4777
0
}
4778
4779
static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
4780
9.00k
{
4781
9.00k
    out_sorted_windows->push_back(window);
4782
9.00k
    if (window->Active)
4783
6.00k
    {
4784
6.00k
        int count = window->DC.ChildWindows.Size;
4785
6.00k
        ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
4786
9.00k
        for (int i = 0; i < count; i++)
4787
3.00k
        {
4788
3.00k
            ImGuiWindow* child = window->DC.ChildWindows[i];
4789
3.00k
            if (child->Active)
4790
3.00k
                AddWindowToSortBuffer(out_sorted_windows, child);
4791
3.00k
        }
4792
6.00k
    }
4793
9.00k
}
4794
4795
static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list)
4796
6.00k
{
4797
6.00k
    if (draw_list->CmdBuffer.Size == 0)
4798
0
        return;
4799
6.00k
    if (draw_list->CmdBuffer.Size == 1 && draw_list->CmdBuffer[0].ElemCount == 0 && draw_list->CmdBuffer[0].UserCallback == NULL)
4800
177
        return;
4801
4802
    // Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc.
4803
    // May trigger for you if you are using PrimXXX functions incorrectly.
4804
5.82k
    IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size);
4805
5.82k
    IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size);
4806
5.82k
    if (!(draw_list->Flags & ImDrawListFlags_AllowVtxOffset))
4807
5.82k
        IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size);
4808
4809
    // Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per ImDrawList = per window)
4810
    // If this assert triggers because you are drawing lots of stuff manually:
4811
    // - First, make sure you are coarse clipping yourself and not trying to draw many things outside visible bounds.
4812
    //   Be mindful that the ImDrawList API doesn't filter vertices. Use the Metrics/Debugger window to inspect draw list contents.
4813
    // - If you want large meshes with more than 64K vertices, you can either:
4814
    //   (A) Handle the ImDrawCmd::VtxOffset value in your renderer backend, and set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset'.
4815
    //       Most example backends already support this from 1.71. Pre-1.71 backends won't.
4816
    //       Some graphics API such as GL ES 1/2 don't have a way to offset the starting vertex so it is not supported for them.
4817
    //   (B) Or handle 32-bit indices in your renderer backend, and uncomment '#define ImDrawIdx unsigned int' line in imconfig.h.
4818
    //       Most example backends already support this. For example, the OpenGL example code detect index size at compile-time:
4819
    //         glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
4820
    //       Your own engine or render API may use different parameters or function calls to specify index sizes.
4821
    //       2 and 4 bytes indices are generally supported by most graphics API.
4822
    // - If for some reason neither of those solutions works for you, a workaround is to call BeginChild()/EndChild() before reaching
4823
    //   the 64K limit to split your draw commands in multiple draw lists.
4824
5.82k
    if (sizeof(ImDrawIdx) == 2)
4825
5.82k
        IM_ASSERT(draw_list->_VtxCurrentIdx < (1 << 16) && "Too many vertices in ImDrawList using 16-bit indices. Read comment above");
4826
4827
5.82k
    out_list->push_back(draw_list);
4828
5.82k
}
4829
4830
static void AddWindowToDrawData(ImGuiWindow* window, int layer)
4831
6.00k
{
4832
6.00k
    ImGuiContext& g = *GImGui;
4833
6.00k
    ImGuiViewportP* viewport = window->Viewport;
4834
6.00k
    g.IO.MetricsRenderWindows++;
4835
6.00k
    if (window->Flags & ImGuiWindowFlags_DockNodeHost)
4836
0
        window->DrawList->ChannelsMerge();
4837
6.00k
    AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[layer], window->DrawList);
4838
9.00k
    for (int i = 0; i < window->DC.ChildWindows.Size; i++)
4839
3.00k
    {
4840
3.00k
        ImGuiWindow* child = window->DC.ChildWindows[i];
4841
3.00k
        if (IsWindowActiveAndVisible(child)) // Clipped children may have been marked not active
4842
3.00k
            AddWindowToDrawData(child, layer);
4843
3.00k
    }
4844
6.00k
}
4845
4846
static inline int GetWindowDisplayLayer(ImGuiWindow* window)
4847
3.00k
{
4848
3.00k
    return (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
4849
3.00k
}
4850
4851
// Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
4852
static inline void AddRootWindowToDrawData(ImGuiWindow* window)
4853
3.00k
{
4854
3.00k
    AddWindowToDrawData(window, GetWindowDisplayLayer(window));
4855
3.00k
}
4856
4857
void ImDrawDataBuilder::FlattenIntoSingleLayer()
4858
3.00k
{
4859
3.00k
    int n = Layers[0].Size;
4860
3.00k
    int size = n;
4861
6.00k
    for (int i = 1; i < IM_ARRAYSIZE(Layers); i++)
4862
3.00k
        size += Layers[i].Size;
4863
3.00k
    Layers[0].resize(size);
4864
6.00k
    for (int layer_n = 1; layer_n < IM_ARRAYSIZE(Layers); layer_n++)
4865
3.00k
    {
4866
3.00k
        ImVector<ImDrawList*>& layer = Layers[layer_n];
4867
3.00k
        if (layer.empty())
4868
3.00k
            continue;
4869
0
        memcpy(&Layers[0][n], &layer[0], layer.Size * sizeof(ImDrawList*));
4870
0
        n += layer.Size;
4871
0
        layer.resize(0);
4872
0
    }
4873
3.00k
}
4874
4875
static void SetupViewportDrawData(ImGuiViewportP* viewport, ImVector<ImDrawList*>* draw_lists)
4876
3.00k
{
4877
    // When minimized, we report draw_data->DisplaySize as zero to be consistent with non-viewport mode,
4878
    // and to allow applications/backends to easily skip rendering.
4879
    // FIXME: Note that we however do NOT attempt to report "zero drawlist / vertices" into the ImDrawData structure.
4880
    // This is because the work has been done already, and its wasted! We should fix that and add optimizations for
4881
    // it earlier in the pipeline, rather than pretend to hide the data at the end of the pipeline.
4882
3.00k
    const bool is_minimized = (viewport->Flags & ImGuiViewportFlags_Minimized) != 0;
4883
4884
3.00k
    ImGuiIO& io = ImGui::GetIO();
4885
3.00k
    ImDrawData* draw_data = &viewport->DrawDataP;
4886
3.00k
    viewport->DrawData = draw_data; // Make publicly accessible
4887
3.00k
    draw_data->Valid = true;
4888
3.00k
    draw_data->CmdLists = (draw_lists->Size > 0) ? draw_lists->Data : NULL;
4889
3.00k
    draw_data->CmdListsCount = draw_lists->Size;
4890
3.00k
    draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
4891
3.00k
    draw_data->DisplayPos = viewport->Pos;
4892
3.00k
    draw_data->DisplaySize = is_minimized ? ImVec2(0.0f, 0.0f) : viewport->Size;
4893
3.00k
    draw_data->FramebufferScale = io.DisplayFramebufferScale; // FIXME-VIEWPORT: This may vary on a per-monitor/viewport basis?
4894
3.00k
    draw_data->OwnerViewport = viewport;
4895
8.82k
    for (int n = 0; n < draw_lists->Size; n++)
4896
5.82k
    {
4897
5.82k
        ImDrawList* draw_list = draw_lists->Data[n];
4898
5.82k
        draw_list->_PopUnusedDrawCmd();
4899
5.82k
        draw_data->TotalVtxCount += draw_list->VtxBuffer.Size;
4900
5.82k
        draw_data->TotalIdxCount += draw_list->IdxBuffer.Size;
4901
5.82k
    }
4902
3.00k
}
4903
4904
// Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering.
4905
// - When using this function it is sane to ensure that float are perfectly rounded to integer values,
4906
//   so that e.g. (int)(max.x-min.x) in user's render produce correct result.
4907
// - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect():
4908
//   some frequently called functions which to modify both channels and clipping simultaneously tend to use the
4909
//   more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds.
4910
void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
4911
18.0k
{
4912
18.0k
    ImGuiWindow* window = GetCurrentWindow();
4913
18.0k
    window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
4914
18.0k
    window->ClipRect = window->DrawList->_ClipRectStack.back();
4915
18.0k
}
4916
4917
void ImGui::PopClipRect()
4918
9.00k
{
4919
9.00k
    ImGuiWindow* window = GetCurrentWindow();
4920
9.00k
    window->DrawList->PopClipRect();
4921
9.00k
    window->ClipRect = window->DrawList->_ClipRectStack.back();
4922
9.00k
}
4923
4924
static ImGuiWindow* FindFrontMostVisibleChildWindow(ImGuiWindow* window)
4925
0
{
4926
0
    for (int n = window->DC.ChildWindows.Size - 1; n >= 0; n--)
4927
0
        if (IsWindowActiveAndVisible(window->DC.ChildWindows[n]))
4928
0
            return FindFrontMostVisibleChildWindow(window->DC.ChildWindows[n]);
4929
0
    return window;
4930
0
}
4931
4932
static void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col)
4933
0
{
4934
0
    if ((col & IM_COL32_A_MASK) == 0)
4935
0
        return;
4936
4937
0
    ImGuiViewportP* viewport = window->Viewport;
4938
0
    ImRect viewport_rect = viewport->GetMainRect();
4939
4940
    // Draw behind window by moving the draw command at the FRONT of the draw list
4941
0
    {
4942
        // We've already called AddWindowToDrawData() which called DrawList->ChannelsMerge() on DockNodeHost windows,
4943
        // and draw list have been trimmed already, hence the explicit recreation of a draw command if missing.
4944
        // FIXME: This is creating complication, might be simpler if we could inject a drawlist in drawdata at a given position and not attempt to manipulate ImDrawCmd order.
4945
0
        ImDrawList* draw_list = window->RootWindowDockTree->DrawList;
4946
0
        if (draw_list->CmdBuffer.Size == 0)
4947
0
            draw_list->AddDrawCmd();
4948
0
        draw_list->PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false); // Ensure ImDrawCmd are not merged
4949
0
        draw_list->AddRectFilled(viewport_rect.Min, viewport_rect.Max, col);
4950
0
        ImDrawCmd cmd = draw_list->CmdBuffer.back();
4951
0
        IM_ASSERT(cmd.ElemCount == 6);
4952
0
        draw_list->CmdBuffer.pop_back();
4953
0
        draw_list->CmdBuffer.push_front(cmd);
4954
0
        draw_list->PopClipRect();
4955
0
        draw_list->AddDrawCmd(); // We need to create a command as CmdBuffer.back().IdxOffset won't be correct if we append to same command.
4956
0
    }
4957
4958
    // Draw over sibling docking nodes in a same docking tree
4959
0
    if (window->RootWindow->DockIsActive)
4960
0
    {
4961
0
        ImDrawList* draw_list = FindFrontMostVisibleChildWindow(window->RootWindowDockTree)->DrawList;
4962
0
        if (draw_list->CmdBuffer.Size == 0)
4963
0
            draw_list->AddDrawCmd();
4964
0
        draw_list->PushClipRect(viewport_rect.Min, viewport_rect.Max, false);
4965
0
        RenderRectFilledWithHole(draw_list, window->RootWindowDockTree->Rect(), window->RootWindow->Rect(), col, 0.0f);// window->RootWindowDockTree->WindowRounding);
4966
0
        draw_list->PopClipRect();
4967
0
    }
4968
0
}
4969
4970
ImGuiWindow* ImGui::FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* parent_window)
4971
0
{
4972
0
    ImGuiContext& g = *GImGui;
4973
0
    ImGuiWindow* bottom_most_visible_window = parent_window;
4974
0
    for (int i = FindWindowDisplayIndex(parent_window); i >= 0; i--)
4975
0
    {
4976
0
        ImGuiWindow* window = g.Windows[i];
4977
0
        if (window->Flags & ImGuiWindowFlags_ChildWindow)
4978
0
            continue;
4979
0
        if (!IsWindowWithinBeginStackOf(window, parent_window))
4980
0
            break;
4981
0
        if (IsWindowActiveAndVisible(window) && GetWindowDisplayLayer(window) <= GetWindowDisplayLayer(parent_window))
4982
0
            bottom_most_visible_window = window;
4983
0
    }
4984
0
    return bottom_most_visible_window;
4985
0
}
4986
4987
static void ImGui::RenderDimmedBackgrounds()
4988
3.00k
{
4989
3.00k
    ImGuiContext& g = *GImGui;
4990
3.00k
    ImGuiWindow* modal_window = GetTopMostAndVisiblePopupModal();
4991
3.00k
    if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
4992
3.00k
        return;
4993
0
    const bool dim_bg_for_modal = (modal_window != NULL);
4994
0
    const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL && g.NavWindowingTargetAnim->Active);
4995
0
    if (!dim_bg_for_modal && !dim_bg_for_window_list)
4996
0
        return;
4997
4998
0
    ImGuiViewport* viewports_already_dimmed[2] = { NULL, NULL };
4999
0
    if (dim_bg_for_modal)
5000
0
    {
5001
        // Draw dimming behind modal or a begin stack child, whichever comes first in draw order.
5002
0
        ImGuiWindow* dim_behind_window = FindBottomMostVisibleWindowWithinBeginStack(modal_window);
5003
0
        RenderDimmedBackgroundBehindWindow(dim_behind_window, GetColorU32(ImGuiCol_ModalWindowDimBg, g.DimBgRatio));
5004
0
        viewports_already_dimmed[0] = modal_window->Viewport;
5005
0
    }
5006
0
    else if (dim_bg_for_window_list)
5007
0
    {
5008
        // Draw dimming behind CTRL+Tab target window and behind CTRL+Tab UI window
5009
0
        RenderDimmedBackgroundBehindWindow(g.NavWindowingTargetAnim, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5010
0
        if (g.NavWindowingListWindow != NULL && g.NavWindowingListWindow->Viewport && g.NavWindowingListWindow->Viewport != g.NavWindowingTargetAnim->Viewport)
5011
0
            RenderDimmedBackgroundBehindWindow(g.NavWindowingListWindow, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5012
0
        viewports_already_dimmed[0] = g.NavWindowingTargetAnim->Viewport;
5013
0
        viewports_already_dimmed[1] = g.NavWindowingListWindow ? g.NavWindowingListWindow->Viewport : NULL;
5014
5015
        // Draw border around CTRL+Tab target window
5016
0
        ImGuiWindow* window = g.NavWindowingTargetAnim;
5017
0
        ImGuiViewport* viewport = window->Viewport;
5018
0
        float distance = g.FontSize;
5019
0
        ImRect bb = window->Rect();
5020
0
        bb.Expand(distance);
5021
0
        if (bb.GetWidth() >= viewport->Size.x && bb.GetHeight() >= viewport->Size.y)
5022
0
            bb.Expand(-distance - 1.0f); // If a window fits the entire viewport, adjust its highlight inward
5023
0
        if (window->DrawList->CmdBuffer.Size == 0)
5024
0
            window->DrawList->AddDrawCmd();
5025
0
        window->DrawList->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size);
5026
0
        window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), window->WindowRounding, 0, 3.0f);
5027
0
        window->DrawList->PopClipRect();
5028
0
    }
5029
5030
    // Draw dimming background on _other_ viewports than the ones our windows are in
5031
0
    for (int viewport_n = 0; viewport_n < g.Viewports.Size; viewport_n++)
5032
0
    {
5033
0
        ImGuiViewportP* viewport = g.Viewports[viewport_n];
5034
0
        if (viewport == viewports_already_dimmed[0] || viewport == viewports_already_dimmed[1])
5035
0
            continue;
5036
0
        if (modal_window && viewport->Window && IsWindowAbove(viewport->Window, modal_window))
5037
0
            continue;
5038
0
        ImDrawList* draw_list = GetForegroundDrawList(viewport);
5039
0
        const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
5040
0
        draw_list->AddRectFilled(viewport->Pos, viewport->Pos + viewport->Size, dim_bg_col);
5041
0
    }
5042
0
}
5043
5044
// This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal.
5045
void ImGui::EndFrame()
5046
6.00k
{
5047
6.00k
    ImGuiContext& g = *GImGui;
5048
6.00k
    IM_ASSERT(g.Initialized);
5049
5050
    // Don't process EndFrame() multiple times.
5051
6.00k
    if (g.FrameCountEnded == g.FrameCount)
5052
3.00k
        return;
5053
3.00k
    IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?");
5054
5055
3.00k
    CallContextHooks(&g, ImGuiContextHookType_EndFramePre);
5056
5057
3.00k
    ErrorCheckEndFrameSanityChecks();
5058
5059
    // Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
5060
3.00k
    if (g.IO.SetPlatformImeDataFn && memcmp(&g.PlatformImeData, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0)
5061
0
    {
5062
0
        ImGuiViewport* viewport = FindViewportByID(g.PlatformImeViewport);
5063
0
        g.IO.SetPlatformImeDataFn(viewport ? viewport : GetMainViewport(), &g.PlatformImeData);
5064
0
    }
5065
5066
    // Hide implicit/fallback "Debug" window if it hasn't been used
5067
3.00k
    g.WithinFrameScopeWithImplicitWindow = false;
5068
3.00k
    if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
5069
3.00k
        g.CurrentWindow->Active = false;
5070
3.00k
    End();
5071
5072
    // Update navigation: CTRL+Tab, wrap-around requests
5073
3.00k
    NavEndFrame();
5074
5075
    // Update docking
5076
3.00k
    DockContextEndFrame(&g);
5077
5078
3.00k
    SetCurrentViewport(NULL, NULL);
5079
5080
    // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
5081
3.00k
    if (g.DragDropActive)
5082
0
    {
5083
0
        bool is_delivered = g.DragDropPayload.Delivery;
5084
0
        bool is_elapsed = (g.DragDropPayload.DataFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(g.DragDropMouseButton));
5085
0
        if (is_delivered || is_elapsed)
5086
0
            ClearDragDrop();
5087
0
    }
5088
5089
    // Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing.
5090
3.00k
    if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
5091
0
    {
5092
0
        g.DragDropWithinSource = true;
5093
0
        SetTooltip("...");
5094
0
        g.DragDropWithinSource = false;
5095
0
    }
5096
5097
    // End frame
5098
3.00k
    g.WithinFrameScope = false;
5099
3.00k
    g.FrameCountEnded = g.FrameCount;
5100
5101
    // Initiate moving window + handle left-click and right-click focus
5102
3.00k
    UpdateMouseMovingWindowEndFrame();
5103
5104
    // Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
5105
3.00k
    UpdateViewportsEndFrame();
5106
5107
    // Sort the window list so that all child windows are after their parent
5108
    // We cannot do that on FocusWindow() because children may not exist yet
5109
3.00k
    g.WindowsTempSortBuffer.resize(0);
5110
3.00k
    g.WindowsTempSortBuffer.reserve(g.Windows.Size);
5111
12.0k
    for (int i = 0; i != g.Windows.Size; i++)
5112
9.00k
    {
5113
9.00k
        ImGuiWindow* window = g.Windows[i];
5114
9.00k
        if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow))       // if a child is active its parent will add it
5115
3.00k
            continue;
5116
6.00k
        AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window);
5117
6.00k
    }
5118
5119
    // This usually assert if there is a mismatch between the ImGuiWindowFlags_ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong.
5120
3.00k
    IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
5121
3.00k
    g.Windows.swap(g.WindowsTempSortBuffer);
5122
3.00k
    g.IO.MetricsActiveWindows = g.WindowsActiveCount;
5123
5124
    // Unlock font atlas
5125
3.00k
    g.IO.Fonts->Locked = false;
5126
5127
    // Clear Input data for next frame
5128
3.00k
    g.IO.AppFocusLost = false;
5129
3.00k
    g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
5130
3.00k
    g.IO.InputQueueCharacters.resize(0);
5131
5132
3.00k
    CallContextHooks(&g, ImGuiContextHookType_EndFramePost);
5133
3.00k
}
5134
5135
// Prepare the data for rendering so you can call GetDrawData()
5136
// (As with anything within the ImGui:: namspace this doesn't touch your GPU or graphics API at all:
5137
// it is the role of the ImGui_ImplXXXX_RenderDrawData() function provided by the renderer backend)
5138
void ImGui::Render()
5139
3.00k
{
5140
3.00k
    ImGuiContext& g = *GImGui;
5141
3.00k
    IM_ASSERT(g.Initialized);
5142
5143
3.00k
    if (g.FrameCountEnded != g.FrameCount)
5144
3.00k
        EndFrame();
5145
3.00k
    const bool first_render_of_frame = (g.FrameCountRendered != g.FrameCount);
5146
3.00k
    g.FrameCountRendered = g.FrameCount;
5147
3.00k
    g.IO.MetricsRenderWindows = 0;
5148
5149
3.00k
    CallContextHooks(&g, ImGuiContextHookType_RenderPre);
5150
5151
    // Add background ImDrawList (for each active viewport)
5152
6.00k
    for (int n = 0; n != g.Viewports.Size; n++)
5153
3.00k
    {
5154
3.00k
        ImGuiViewportP* viewport = g.Viewports[n];
5155
3.00k
        viewport->DrawDataBuilder.Clear();
5156
3.00k
        if (viewport->DrawLists[0] != NULL)
5157
0
            AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[0], GetBackgroundDrawList(viewport));
5158
3.00k
    }
5159
5160
    // Add ImDrawList to render
5161
3.00k
    ImGuiWindow* windows_to_render_top_most[2];
5162
3.00k
    windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindowDockTree : NULL;
5163
3.00k
    windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL);
5164
12.0k
    for (int n = 0; n != g.Windows.Size; n++)
5165
9.00k
    {
5166
9.00k
        ImGuiWindow* window = g.Windows[n];
5167
9.00k
        IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
5168
9.00k
        if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
5169
3.00k
            AddRootWindowToDrawData(window);
5170
9.00k
    }
5171
9.00k
    for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
5172
6.00k
        if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
5173
0
            AddRootWindowToDrawData(windows_to_render_top_most[n]);
5174
5175
    // Draw modal/window whitening backgrounds
5176
3.00k
    if (first_render_of_frame)
5177
3.00k
        RenderDimmedBackgrounds();
5178
5179
    // Draw software mouse cursor if requested by io.MouseDrawCursor flag
5180
3.00k
    if (g.IO.MouseDrawCursor && first_render_of_frame && g.MouseCursor != ImGuiMouseCursor_None)
5181
0
        RenderMouseCursor(g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
5182
5183
    // Setup ImDrawData structures for end-user
5184
3.00k
    g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;
5185
6.00k
    for (int n = 0; n < g.Viewports.Size; n++)
5186
3.00k
    {
5187
3.00k
        ImGuiViewportP* viewport = g.Viewports[n];
5188
3.00k
        viewport->DrawDataBuilder.FlattenIntoSingleLayer();
5189
5190
        // Add foreground ImDrawList (for each active viewport)
5191
3.00k
        if (viewport->DrawLists[1] != NULL)
5192
0
            AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[0], GetForegroundDrawList(viewport));
5193
5194
3.00k
        SetupViewportDrawData(viewport, &viewport->DrawDataBuilder.Layers[0]);
5195
3.00k
        ImDrawData* draw_data = viewport->DrawData;
5196
3.00k
        g.IO.MetricsRenderVertices += draw_data->TotalVtxCount;
5197
3.00k
        g.IO.MetricsRenderIndices += draw_data->TotalIdxCount;
5198
3.00k
    }
5199
5200
3.00k
    CallContextHooks(&g, ImGuiContextHookType_RenderPost);
5201
3.00k
}
5202
5203
// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
5204
// CalcTextSize("") should return ImVec2(0.0f, g.FontSize)
5205
ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
5206
6.00k
{
5207
6.00k
    ImGuiContext& g = *GImGui;
5208
5209
6.00k
    const char* text_display_end;
5210
6.00k
    if (hide_text_after_double_hash)
5211
6.00k
        text_display_end = FindRenderedTextEnd(text, text_end);      // Hide anything after a '##' string
5212
0
    else
5213
0
        text_display_end = text_end;
5214
5215
6.00k
    ImFont* font = g.Font;
5216
6.00k
    const float font_size = g.FontSize;
5217
6.00k
    if (text == text_display_end)
5218
0
        return ImVec2(0.0f, font_size);
5219
6.00k
    ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
5220
5221
    // Round
5222
    // FIXME: This has been here since Dec 2015 (7b0bf230) but down the line we want this out.
5223
    // FIXME: Investigate using ceilf or e.g.
5224
    // - https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c
5225
    // - https://embarkstudios.github.io/rust-gpu/api/src/libm/math/ceilf.rs.html
5226
6.00k
    text_size.x = IM_FLOOR(text_size.x + 0.99999f);
5227
5228
6.00k
    return text_size;
5229
6.00k
}
5230
5231
// Find window given position, search front-to-back
5232
// FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically
5233
// with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
5234
// called, aka before the next Begin(). Moving window isn't affected.
5235
static void FindHoveredWindow()
5236
3.00k
{
5237
3.00k
    ImGuiContext& g = *GImGui;
5238
5239
    // Special handling for the window being moved: Ignore the mouse viewport check (because it may reset/lose its viewport during the undocking frame)
5240
3.00k
    ImGuiViewportP* moving_window_viewport = g.MovingWindow ? g.MovingWindow->Viewport : NULL;
5241
3.00k
    if (g.MovingWindow)
5242
0
        g.MovingWindow->Viewport = g.MouseViewport;
5243
5244
3.00k
    ImGuiWindow* hovered_window = NULL;
5245
3.00k
    ImGuiWindow* hovered_window_ignoring_moving_window = NULL;
5246
3.00k
    if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
5247
0
        hovered_window = g.MovingWindow;
5248
5249
3.00k
    ImVec2 padding_regular = g.Style.TouchExtraPadding;
5250
3.00k
    ImVec2 padding_for_resize = g.IO.ConfigWindowsResizeFromEdges ? g.WindowsHoverPadding : padding_regular;
5251
11.9k
    for (int i = g.Windows.Size - 1; i >= 0; i--)
5252
8.99k
    {
5253
8.99k
        ImGuiWindow* window = g.Windows[i];
5254
8.99k
        IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5255
8.99k
        if (!window->Active || window->Hidden)
5256
2.99k
            continue;
5257
6.00k
        if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
5258
0
            continue;
5259
6.00k
        IM_ASSERT(window->Viewport);
5260
6.00k
        if (window->Viewport != g.MouseViewport)
5261
0
            continue;
5262
5263
        // Using the clipped AABB, a child window will typically be clipped by its parent (not always)
5264
6.00k
        ImRect bb(window->OuterRectClipped);
5265
6.00k
        if (window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize))
5266
3.00k
            bb.Expand(padding_regular);
5267
3.00k
        else
5268
3.00k
            bb.Expand(padding_for_resize);
5269
6.00k
        if (!bb.Contains(g.IO.MousePos))
5270
5.99k
            continue;
5271
5272
        // Support for one rectangular hole in any given window
5273
        // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
5274
5
        if (window->HitTestHoleSize.x != 0)
5275
0
        {
5276
0
            ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y);
5277
0
            ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y);
5278
0
            if (ImRect(hole_pos, hole_pos + hole_size).Contains(g.IO.MousePos))
5279
0
                continue;
5280
0
        }
5281
5282
5
        if (hovered_window == NULL)
5283
5
            hovered_window = window;
5284
5
        IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5285
5
        if (hovered_window_ignoring_moving_window == NULL && (!g.MovingWindow || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree))
5286
5
            hovered_window_ignoring_moving_window = window;
5287
5
        if (hovered_window && hovered_window_ignoring_moving_window)
5288
5
            break;
5289
5
    }
5290
5291
3.00k
    g.HoveredWindow = hovered_window;
5292
3.00k
    g.HoveredWindowUnderMovingWindow = hovered_window_ignoring_moving_window;
5293
5294
3.00k
    if (g.MovingWindow)
5295
0
        g.MovingWindow->Viewport = moving_window_viewport;
5296
3.00k
}
5297
5298
bool ImGui::IsItemActive()
5299
6.00k
{
5300
6.00k
    ImGuiContext& g = *GImGui;
5301
6.00k
    if (g.ActiveId)
5302
0
        return g.ActiveId == g.LastItemData.ID;
5303
6.00k
    return false;
5304
6.00k
}
5305
5306
bool ImGui::IsItemActivated()
5307
0
{
5308
0
    ImGuiContext& g = *GImGui;
5309
0
    if (g.ActiveId)
5310
0
        if (g.ActiveId == g.LastItemData.ID && g.ActiveIdPreviousFrame != g.LastItemData.ID)
5311
0
            return true;
5312
0
    return false;
5313
0
}
5314
5315
bool ImGui::IsItemDeactivated()
5316
0
{
5317
0
    ImGuiContext& g = *GImGui;
5318
0
    if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDeactivated)
5319
0
        return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
5320
0
    return (g.ActiveIdPreviousFrame == g.LastItemData.ID && g.ActiveIdPreviousFrame != 0 && g.ActiveId != g.LastItemData.ID);
5321
0
}
5322
5323
bool ImGui::IsItemDeactivatedAfterEdit()
5324
0
{
5325
0
    ImGuiContext& g = *GImGui;
5326
0
    return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore));
5327
0
}
5328
5329
// == GetItemID() == GetFocusID()
5330
bool ImGui::IsItemFocused()
5331
0
{
5332
0
    ImGuiContext& g = *GImGui;
5333
0
    if (g.NavId != g.LastItemData.ID || g.NavId == 0)
5334
0
        return false;
5335
5336
    // Special handling for the dummy item after Begin() which represent the title bar or tab.
5337
    // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
5338
0
    ImGuiWindow* window = g.CurrentWindow;
5339
0
    if (g.LastItemData.ID == window->ID && window->WriteAccessed)
5340
0
        return false;
5341
5342
0
    return true;
5343
0
}
5344
5345
// Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()!
5346
// Most widgets have specific reactions based on mouse-up/down state, mouse position etc.
5347
bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
5348
0
{
5349
0
    return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
5350
0
}
5351
5352
bool ImGui::IsItemToggledOpen()
5353
0
{
5354
0
    ImGuiContext& g = *GImGui;
5355
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
5356
0
}
5357
5358
bool ImGui::IsItemToggledSelection()
5359
0
{
5360
0
    ImGuiContext& g = *GImGui;
5361
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
5362
0
}
5363
5364
bool ImGui::IsAnyItemHovered()
5365
0
{
5366
0
    ImGuiContext& g = *GImGui;
5367
0
    return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
5368
0
}
5369
5370
bool ImGui::IsAnyItemActive()
5371
0
{
5372
0
    ImGuiContext& g = *GImGui;
5373
0
    return g.ActiveId != 0;
5374
0
}
5375
5376
bool ImGui::IsAnyItemFocused()
5377
0
{
5378
0
    ImGuiContext& g = *GImGui;
5379
0
    return g.NavId != 0 && !g.NavDisableHighlight;
5380
0
}
5381
5382
bool ImGui::IsItemVisible()
5383
0
{
5384
0
    ImGuiContext& g = *GImGui;
5385
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) != 0;
5386
0
}
5387
5388
bool ImGui::IsItemEdited()
5389
0
{
5390
0
    ImGuiContext& g = *GImGui;
5391
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Edited) != 0;
5392
0
}
5393
5394
// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
5395
// FIXME: Although this is exposed, its interaction and ideal idiom with using ImGuiButtonFlags_AllowItemOverlap flag are extremely confusing, need rework.
5396
void ImGui::SetItemAllowOverlap()
5397
0
{
5398
0
    ImGuiContext& g = *GImGui;
5399
0
    ImGuiID id = g.LastItemData.ID;
5400
0
    if (g.HoveredId == id)
5401
0
        g.HoveredIdAllowOverlap = true;
5402
0
    if (g.ActiveId == id)
5403
0
        g.ActiveIdAllowOverlap = true;
5404
0
}
5405
5406
// FIXME: It might be undesirable that this will likely disable KeyOwner-aware shortcuts systems. Consider a more fine-tuned version for the two users of this function.
5407
void ImGui::SetActiveIdUsingAllKeyboardKeys()
5408
0
{
5409
0
    ImGuiContext& g = *GImGui;
5410
0
    IM_ASSERT(g.ActiveId != 0);
5411
0
    g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_COUNT) - 1;
5412
0
    g.ActiveIdUsingAllKeyboardKeys = true;
5413
0
    NavMoveRequestCancel();
5414
0
}
5415
5416
ImGuiID ImGui::GetItemID()
5417
0
{
5418
0
    ImGuiContext& g = *GImGui;
5419
0
    return g.LastItemData.ID;
5420
0
}
5421
5422
ImVec2 ImGui::GetItemRectMin()
5423
0
{
5424
0
    ImGuiContext& g = *GImGui;
5425
0
    return g.LastItemData.Rect.Min;
5426
0
}
5427
5428
ImVec2 ImGui::GetItemRectMax()
5429
0
{
5430
0
    ImGuiContext& g = *GImGui;
5431
0
    return g.LastItemData.Rect.Max;
5432
0
}
5433
5434
ImVec2 ImGui::GetItemRectSize()
5435
0
{
5436
0
    ImGuiContext& g = *GImGui;
5437
0
    return g.LastItemData.Rect.GetSize();
5438
0
}
5439
5440
bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags)
5441
3.00k
{
5442
3.00k
    ImGuiContext& g = *GImGui;
5443
3.00k
    ImGuiWindow* parent_window = g.CurrentWindow;
5444
5445
3.00k
    flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoDocking;
5446
3.00k
    flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove);  // Inherit the NoMove flag
5447
5448
    // Size
5449
3.00k
    const ImVec2 content_avail = GetContentRegionAvail();
5450
3.00k
    ImVec2 size = ImFloor(size_arg);
5451
3.00k
    const int auto_fit_axises = ((size.x == 0.0f) ? (1 << ImGuiAxis_X) : 0x00) | ((size.y == 0.0f) ? (1 << ImGuiAxis_Y) : 0x00);
5452
3.00k
    if (size.x <= 0.0f)
5453
2.96k
        size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too many issues)
5454
3.00k
    if (size.y <= 0.0f)
5455
2.69k
        size.y = ImMax(content_avail.y + size.y, 4.0f);
5456
3.00k
    SetNextWindowSize(size);
5457
5458
    // Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value.
5459
3.00k
    const char* temp_window_name;
5460
3.00k
    if (name)
5461
3.00k
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s_%08X", parent_window->Name, name, id);
5462
0
    else
5463
0
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%08X", parent_window->Name, id);
5464
5465
3.00k
    const float backup_border_size = g.Style.ChildBorderSize;
5466
3.00k
    if (!border)
5467
2.02k
        g.Style.ChildBorderSize = 0.0f;
5468
3.00k
    bool ret = Begin(temp_window_name, NULL, flags);
5469
3.00k
    g.Style.ChildBorderSize = backup_border_size;
5470
5471
3.00k
    ImGuiWindow* child_window = g.CurrentWindow;
5472
3.00k
    child_window->ChildId = id;
5473
3.00k
    child_window->AutoFitChildAxises = (ImS8)auto_fit_axises;
5474
5475
    // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
5476
    // While this is not really documented/defined, it seems that the expected thing to do.
5477
3.00k
    if (child_window->BeginCount == 1)
5478
3.00k
        parent_window->DC.CursorPos = child_window->Pos;
5479
5480
    // Process navigation-in immediately so NavInit can run on first frame
5481
3.00k
    if (g.NavActivateId == id && !(flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavHasScroll))
5482
0
    {
5483
0
        FocusWindow(child_window);
5484
0
        NavInitWindow(child_window, false);
5485
0
        SetActiveID(id + 1, child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item
5486
0
        g.ActiveIdSource = ImGuiInputSource_Nav;
5487
0
    }
5488
3.00k
    return ret;
5489
3.00k
}
5490
5491
bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
5492
3.00k
{
5493
3.00k
    ImGuiWindow* window = GetCurrentWindow();
5494
3.00k
    return BeginChildEx(str_id, window->GetID(str_id), size_arg, border, extra_flags);
5495
3.00k
}
5496
5497
bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
5498
0
{
5499
0
    IM_ASSERT(id != 0);
5500
0
    return BeginChildEx(NULL, id, size_arg, border, extra_flags);
5501
0
}
5502
5503
void ImGui::EndChild()
5504
3.00k
{
5505
3.00k
    ImGuiContext& g = *GImGui;
5506
3.00k
    ImGuiWindow* window = g.CurrentWindow;
5507
5508
3.00k
    IM_ASSERT(g.WithinEndChild == false);
5509
3.00k
    IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow);   // Mismatched BeginChild()/EndChild() calls
5510
5511
3.00k
    g.WithinEndChild = true;
5512
3.00k
    if (window->BeginCount > 1)
5513
0
    {
5514
0
        End();
5515
0
    }
5516
3.00k
    else
5517
3.00k
    {
5518
3.00k
        ImVec2 sz = window->Size;
5519
3.00k
        if (window->AutoFitChildAxises & (1 << ImGuiAxis_X)) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f
5520
2.96k
            sz.x = ImMax(4.0f, sz.x);
5521
3.00k
        if (window->AutoFitChildAxises & (1 << ImGuiAxis_Y))
5522
2.69k
            sz.y = ImMax(4.0f, sz.y);
5523
3.00k
        End();
5524
5525
3.00k
        ImGuiWindow* parent_window = g.CurrentWindow;
5526
3.00k
        ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + sz);
5527
3.00k
        ItemSize(sz);
5528
3.00k
        if ((window->DC.NavLayersActiveMask != 0 || window->DC.NavHasScroll) && !(window->Flags & ImGuiWindowFlags_NavFlattened))
5529
2.91k
        {
5530
2.91k
            ItemAdd(bb, window->ChildId);
5531
2.91k
            RenderNavHighlight(bb, window->ChildId);
5532
5533
            // When browsing a window that has no activable items (scroll only) we keep a highlight on the child (pass g.NavId to trick into always displaying)
5534
2.91k
            if (window->DC.NavLayersActiveMask == 0 && window == g.NavWindow)
5535
2.47k
                RenderNavHighlight(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavHighlightFlags_TypeThin);
5536
2.91k
        }
5537
92
        else
5538
92
        {
5539
            // Not navigable into
5540
92
            ItemAdd(bb, 0);
5541
92
        }
5542
3.00k
        if (g.HoveredWindow == window)
5543
0
            g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
5544
3.00k
    }
5545
3.00k
    g.WithinEndChild = false;
5546
3.00k
    g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
5547
3.00k
}
5548
5549
// Helper to create a child window / scrolling region that looks like a normal widget frame.
5550
bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags)
5551
0
{
5552
0
    ImGuiContext& g = *GImGui;
5553
0
    const ImGuiStyle& style = g.Style;
5554
0
    PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]);
5555
0
    PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding);
5556
0
    PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize);
5557
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);
5558
0
    bool ret = BeginChild(id, size, true, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags);
5559
0
    PopStyleVar(3);
5560
0
    PopStyleColor();
5561
0
    return ret;
5562
0
}
5563
5564
void ImGui::EndChildFrame()
5565
0
{
5566
0
    EndChild();
5567
0
}
5568
5569
static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
5570
6
{
5571
6
    window->SetWindowPosAllowFlags       = enabled ? (window->SetWindowPosAllowFlags       | flags) : (window->SetWindowPosAllowFlags       & ~flags);
5572
6
    window->SetWindowSizeAllowFlags      = enabled ? (window->SetWindowSizeAllowFlags      | flags) : (window->SetWindowSizeAllowFlags      & ~flags);
5573
6
    window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
5574
6
    window->SetWindowDockAllowFlags      = enabled ? (window->SetWindowDockAllowFlags      | flags) : (window->SetWindowDockAllowFlags      & ~flags);
5575
6
}
5576
5577
ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
5578
9.00k
{
5579
9.00k
    ImGuiContext& g = *GImGui;
5580
9.00k
    return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
5581
9.00k
}
5582
5583
ImGuiWindow* ImGui::FindWindowByName(const char* name)
5584
9.00k
{
5585
9.00k
    ImGuiID id = ImHashStr(name);
5586
9.00k
    return FindWindowByID(id);
5587
9.00k
}
5588
5589
static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
5590
0
{
5591
0
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
5592
0
    window->ViewportPos = main_viewport->Pos;
5593
0
    if (settings->ViewportId)
5594
0
    {
5595
0
        window->ViewportId = settings->ViewportId;
5596
0
        window->ViewportPos = ImVec2(settings->ViewportPos.x, settings->ViewportPos.y);
5597
0
    }
5598
0
    window->Pos = ImFloor(ImVec2(settings->Pos.x + window->ViewportPos.x, settings->Pos.y + window->ViewportPos.y));
5599
0
    if (settings->Size.x > 0 && settings->Size.y > 0)
5600
0
        window->Size = window->SizeFull = ImFloor(ImVec2(settings->Size.x, settings->Size.y));
5601
0
    window->Collapsed = settings->Collapsed;
5602
0
    window->DockId = settings->DockId;
5603
0
    window->DockOrder = settings->DockOrder;
5604
0
}
5605
5606
static void UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags)
5607
9.00k
{
5608
9.00k
    ImGuiContext& g = *GImGui;
5609
5610
9.00k
    const bool new_is_explicit_child = (new_flags & ImGuiWindowFlags_ChildWindow) != 0 && ((new_flags & ImGuiWindowFlags_Popup) == 0 || (new_flags & ImGuiWindowFlags_ChildMenu) != 0);
5611
9.00k
    const bool child_flag_changed = new_is_explicit_child != window->IsExplicitChild;
5612
9.00k
    if ((just_created || child_flag_changed) && !new_is_explicit_child)
5613
2
    {
5614
2
        IM_ASSERT(!g.WindowsFocusOrder.contains(window));
5615
2
        g.WindowsFocusOrder.push_back(window);
5616
2
        window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1);
5617
2
    }
5618
9.00k
    else if (!just_created && child_flag_changed && new_is_explicit_child)
5619
0
    {
5620
0
        IM_ASSERT(g.WindowsFocusOrder[window->FocusOrder] == window);
5621
0
        for (int n = window->FocusOrder + 1; n < g.WindowsFocusOrder.Size; n++)
5622
0
            g.WindowsFocusOrder[n]->FocusOrder--;
5623
0
        g.WindowsFocusOrder.erase(g.WindowsFocusOrder.Data + window->FocusOrder);
5624
0
        window->FocusOrder = -1;
5625
0
    }
5626
9.00k
    window->IsExplicitChild = new_is_explicit_child;
5627
9.00k
}
5628
5629
static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags)
5630
3
{
5631
3
    ImGuiContext& g = *GImGui;
5632
    //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
5633
5634
    // Create window the first time
5635
3
    ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
5636
3
    window->Flags = flags;
5637
3
    g.WindowsById.SetVoidPtr(window->ID, window);
5638
5639
    // Default/arbitrary window position. Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
5640
3
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
5641
3
    window->Pos = main_viewport->Pos + ImVec2(60, 60);
5642
3
    window->ViewportPos = main_viewport->Pos;
5643
5644
    // User can disable loading and saving of settings. Tooltip and child windows also don't store settings.
5645
3
    if (!(flags & ImGuiWindowFlags_NoSavedSettings))
5646
2
        if (ImGuiWindowSettings* settings = ImGui::FindWindowSettings(window->ID))
5647
0
        {
5648
            // Retrieve settings from .ini file
5649
0
            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
5650
0
            SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
5651
0
            ApplyWindowSettings(window, settings);
5652
0
        }
5653
3
    window->DC.CursorStartPos = window->DC.CursorMaxPos = window->DC.IdealMaxPos = window->Pos; // So first call to CalcWindowContentSizes() doesn't return crazy values
5654
5655
3
    if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
5656
0
    {
5657
0
        window->AutoFitFramesX = window->AutoFitFramesY = 2;
5658
0
        window->AutoFitOnlyGrows = false;
5659
0
    }
5660
3
    else
5661
3
    {
5662
3
        if (window->Size.x <= 0.0f)
5663
3
            window->AutoFitFramesX = 2;
5664
3
        if (window->Size.y <= 0.0f)
5665
3
            window->AutoFitFramesY = 2;
5666
3
        window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
5667
3
    }
5668
5669
3
    if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
5670
0
        g.Windows.push_front(window); // Quite slow but rare and only once
5671
3
    else
5672
3
        g.Windows.push_back(window);
5673
5674
3
    return window;
5675
3
}
5676
5677
static ImGuiWindow* GetWindowForTitleDisplay(ImGuiWindow* window)
5678
0
{
5679
0
    return window->DockNodeAsHost ? window->DockNodeAsHost->VisibleWindow : window;
5680
0
}
5681
5682
static ImGuiWindow* GetWindowForTitleAndMenuHeight(ImGuiWindow* window)
5683
12.0k
{
5684
12.0k
    return (window->DockNodeAsHost && window->DockNodeAsHost->VisibleWindow) ? window->DockNodeAsHost->VisibleWindow : window;
5685
12.0k
}
5686
5687
static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, const ImVec2& size_desired)
5688
18.0k
{
5689
18.0k
    ImGuiContext& g = *GImGui;
5690
18.0k
    ImVec2 new_size = size_desired;
5691
18.0k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)
5692
0
    {
5693
        // Using -1,-1 on either X/Y axis to preserve the current size.
5694
0
        ImRect cr = g.NextWindowData.SizeConstraintRect;
5695
0
        new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
5696
0
        new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
5697
0
        if (g.NextWindowData.SizeCallback)
5698
0
        {
5699
0
            ImGuiSizeCallbackData data;
5700
0
            data.UserData = g.NextWindowData.SizeCallbackUserData;
5701
0
            data.Pos = window->Pos;
5702
0
            data.CurrentSize = window->SizeFull;
5703
0
            data.DesiredSize = new_size;
5704
0
            g.NextWindowData.SizeCallback(&data);
5705
0
            new_size = data.DesiredSize;
5706
0
        }
5707
0
        new_size.x = IM_FLOOR(new_size.x);
5708
0
        new_size.y = IM_FLOOR(new_size.y);
5709
0
    }
5710
5711
    // Minimum size
5712
18.0k
    if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize)))
5713
12.0k
    {
5714
12.0k
        ImGuiWindow* window_for_height = GetWindowForTitleAndMenuHeight(window);
5715
12.0k
        new_size = ImMax(new_size, g.Style.WindowMinSize);
5716
12.0k
        const float minimum_height = window_for_height->TitleBarHeight() + window_for_height->MenuBarHeight() + ImMax(0.0f, g.Style.WindowRounding - 1.0f);
5717
12.0k
        new_size.y = ImMax(new_size.y, minimum_height); // Reduce artifacts with very small windows
5718
12.0k
    }
5719
18.0k
    return new_size;
5720
18.0k
}
5721
5722
static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_current, ImVec2* content_size_ideal)
5723
9.00k
{
5724
9.00k
    bool preserve_old_content_sizes = false;
5725
9.00k
    if (window->Collapsed && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
5726
0
        preserve_old_content_sizes = true;
5727
9.00k
    else if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
5728
0
        preserve_old_content_sizes = true;
5729
9.00k
    if (preserve_old_content_sizes)
5730
0
    {
5731
0
        *content_size_current = window->ContentSize;
5732
0
        *content_size_ideal = window->ContentSizeIdeal;
5733
0
        return;
5734
0
    }
5735
5736
9.00k
    content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_FLOOR(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
5737
9.00k
    content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_FLOOR(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
5738
9.00k
    content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_FLOOR(ImMax(window->DC.CursorMaxPos.x, window->DC.IdealMaxPos.x) - window->DC.CursorStartPos.x);
5739
9.00k
    content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_FLOOR(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y);
5740
9.00k
}
5741
5742
static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
5743
9.00k
{
5744
9.00k
    ImGuiContext& g = *GImGui;
5745
9.00k
    ImGuiStyle& style = g.Style;
5746
9.00k
    const float decoration_w_without_scrollbars = window->DecoOuterSizeX1 + window->DecoOuterSizeX2 - window->ScrollbarSizes.x;
5747
9.00k
    const float decoration_h_without_scrollbars = window->DecoOuterSizeY1 + window->DecoOuterSizeY2 - window->ScrollbarSizes.y;
5748
9.00k
    ImVec2 size_pad = window->WindowPadding * 2.0f;
5749
9.00k
    ImVec2 size_desired = size_contents + size_pad + ImVec2(decoration_w_without_scrollbars, decoration_h_without_scrollbars);
5750
9.00k
    if (window->Flags & ImGuiWindowFlags_Tooltip)
5751
0
    {
5752
        // Tooltip always resize
5753
0
        return size_desired;
5754
0
    }
5755
9.00k
    else
5756
9.00k
    {
5757
        // Maximum window size is determined by the viewport size or monitor size
5758
9.00k
        const bool is_popup = (window->Flags & ImGuiWindowFlags_Popup) != 0;
5759
9.00k
        const bool is_menu = (window->Flags & ImGuiWindowFlags_ChildMenu) != 0;
5760
9.00k
        ImVec2 size_min = style.WindowMinSize;
5761
9.00k
        if (is_popup || is_menu) // Popups and menus bypass style.WindowMinSize by default, but we give then a non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
5762
0
            size_min = ImMin(size_min, ImVec2(4.0f, 4.0f));
5763
5764
9.00k
        ImVec2 avail_size = window->Viewport->WorkSize;
5765
9.00k
        if (window->ViewportOwned)
5766
0
            avail_size = ImVec2(FLT_MAX, FLT_MAX);
5767
9.00k
        const int monitor_idx = window->ViewportAllowPlatformMonitorExtend;
5768
9.00k
        if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
5769
0
            avail_size = g.PlatformIO.Monitors[monitor_idx].WorkSize;
5770
9.00k
        ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, avail_size - style.DisplaySafeAreaPadding * 2.0f));
5771
5772
        // When the window cannot fit all contents (either because of constraints, either because screen is too small),
5773
        // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
5774
9.00k
        ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit);
5775
9.00k
        bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - decoration_w_without_scrollbars < size_contents.x  && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar);
5776
9.00k
        bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - decoration_h_without_scrollbars < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar);
5777
9.00k
        if (will_have_scrollbar_x)
5778
3.00k
            size_auto_fit.y += style.ScrollbarSize;
5779
9.00k
        if (will_have_scrollbar_y)
5780
12
            size_auto_fit.x += style.ScrollbarSize;
5781
9.00k
        return size_auto_fit;
5782
9.00k
    }
5783
9.00k
}
5784
5785
ImVec2 ImGui::CalcWindowNextAutoFitSize(ImGuiWindow* window)
5786
0
{
5787
0
    ImVec2 size_contents_current;
5788
0
    ImVec2 size_contents_ideal;
5789
0
    CalcWindowContentSizes(window, &size_contents_current, &size_contents_ideal);
5790
0
    ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents_ideal);
5791
0
    ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit);
5792
0
    return size_final;
5793
0
}
5794
5795
static ImGuiCol GetWindowBgColorIdx(ImGuiWindow* window)
5796
9.00k
{
5797
9.00k
    if (window->Flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
5798
0
        return ImGuiCol_PopupBg;
5799
9.00k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !window->DockIsActive)
5800
3.00k
        return ImGuiCol_ChildBg;
5801
6.00k
    return ImGuiCol_WindowBg;
5802
9.00k
}
5803
5804
static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
5805
0
{
5806
0
    ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm);                // Expected window upper-left
5807
0
    ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
5808
0
    ImVec2 size_expected = pos_max - pos_min;
5809
0
    ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected);
5810
0
    *out_pos = pos_min;
5811
0
    if (corner_norm.x == 0.0f)
5812
0
        out_pos->x -= (size_constrained.x - size_expected.x);
5813
0
    if (corner_norm.y == 0.0f)
5814
0
        out_pos->y -= (size_constrained.y - size_expected.y);
5815
0
    *out_size = size_constrained;
5816
0
}
5817
5818
// Data for resizing from corner
5819
struct ImGuiResizeGripDef
5820
{
5821
    ImVec2  CornerPosN;
5822
    ImVec2  InnerDir;
5823
    int     AngleMin12, AngleMax12;
5824
};
5825
static const ImGuiResizeGripDef resize_grip_def[4] =
5826
{
5827
    { ImVec2(1, 1), ImVec2(-1, -1), 0, 3 },  // Lower-right
5828
    { ImVec2(0, 1), ImVec2(+1, -1), 3, 6 },  // Lower-left
5829
    { ImVec2(0, 0), ImVec2(+1, +1), 6, 9 },  // Upper-left (Unused)
5830
    { ImVec2(1, 0), ImVec2(-1, +1), 9, 12 }  // Upper-right (Unused)
5831
};
5832
5833
// Data for resizing from borders
5834
struct ImGuiResizeBorderDef
5835
{
5836
    ImVec2 InnerDir;
5837
    ImVec2 SegmentN1, SegmentN2;
5838
    float  OuterAngle;
5839
};
5840
static const ImGuiResizeBorderDef resize_border_def[4] =
5841
{
5842
    { ImVec2(+1, 0), ImVec2(0, 1), ImVec2(0, 0), IM_PI * 1.00f }, // Left
5843
    { ImVec2(-1, 0), ImVec2(1, 0), ImVec2(1, 1), IM_PI * 0.00f }, // Right
5844
    { ImVec2(0, +1), ImVec2(0, 0), ImVec2(1, 0), IM_PI * 1.50f }, // Up
5845
    { ImVec2(0, -1), ImVec2(1, 1), ImVec2(0, 1), IM_PI * 0.50f }  // Down
5846
};
5847
5848
static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
5849
0
{
5850
0
    ImRect rect = window->Rect();
5851
0
    if (thickness == 0.0f)
5852
0
        rect.Max -= ImVec2(1, 1);
5853
0
    if (border_n == ImGuiDir_Left)  { return ImRect(rect.Min.x - thickness,    rect.Min.y + perp_padding, rect.Min.x + thickness,    rect.Max.y - perp_padding); }
5854
0
    if (border_n == ImGuiDir_Right) { return ImRect(rect.Max.x - thickness,    rect.Min.y + perp_padding, rect.Max.x + thickness,    rect.Max.y - perp_padding); }
5855
0
    if (border_n == ImGuiDir_Up)    { return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness,    rect.Max.x - perp_padding, rect.Min.y + thickness);    }
5856
0
    if (border_n == ImGuiDir_Down)  { return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness,    rect.Max.x - perp_padding, rect.Max.y + thickness);    }
5857
0
    IM_ASSERT(0);
5858
0
    return ImRect();
5859
0
}
5860
5861
// 0..3: corners (Lower-right, Lower-left, Unused, Unused)
5862
ImGuiID ImGui::GetWindowResizeCornerID(ImGuiWindow* window, int n)
5863
0
{
5864
0
    IM_ASSERT(n >= 0 && n < 4);
5865
0
    ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
5866
0
    id = ImHashStr("#RESIZE", 0, id);
5867
0
    id = ImHashData(&n, sizeof(int), id);
5868
0
    return id;
5869
0
}
5870
5871
// Borders (Left, Right, Up, Down)
5872
ImGuiID ImGui::GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir)
5873
0
{
5874
0
    IM_ASSERT(dir >= 0 && dir < 4);
5875
0
    int n = (int)dir + 4;
5876
0
    ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
5877
0
    id = ImHashStr("#RESIZE", 0, id);
5878
0
    id = ImHashData(&n, sizeof(int), id);
5879
0
    return id;
5880
0
}
5881
5882
// Handle resize for: Resize Grips, Borders, Gamepad
5883
// Return true when using auto-fit (double-click on resize grip)
5884
static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect)
5885
9.00k
{
5886
9.00k
    ImGuiContext& g = *GImGui;
5887
9.00k
    ImGuiWindowFlags flags = window->Flags;
5888
5889
9.00k
    if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
5890
3.00k
        return false;
5891
6.00k
    if (window->WasActive == false) // Early out to avoid running this code for e.g. a hidden implicit/fallback Debug window.
5892
3.00k
        return false;
5893
5894
3.00k
    bool ret_auto_fit = false;
5895
3.00k
    const int resize_border_count = g.IO.ConfigWindowsResizeFromEdges ? 4 : 0;
5896
3.00k
    const float grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
5897
3.00k
    const float grip_hover_inner_size = IM_FLOOR(grip_draw_size * 0.75f);
5898
3.00k
    const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_HOVER_PADDING : 0.0f;
5899
5900
3.00k
    ImVec2 pos_target(FLT_MAX, FLT_MAX);
5901
3.00k
    ImVec2 size_target(FLT_MAX, FLT_MAX);
5902
5903
    // Clip mouse interaction rectangles within the viewport rectangle (in practice the narrowing is going to happen most of the time).
5904
    // - Not narrowing would mostly benefit the situation where OS windows _without_ decoration have a threshold for hovering when outside their limits.
5905
    //   This is however not the case with current backends under Win32, but a custom borderless window implementation would benefit from it.
5906
    // - When decoration are enabled we typically benefit from that distance, but then our resize elements would be conflicting with OS resize elements, so we also narrow.
5907
    // - Note that we are unable to tell if the platform setup allows hovering with a distance threshold (on Win32, decorated window have such threshold).
5908
    // We only clip interaction so we overwrite window->ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup.
5909
3.00k
    const bool clip_with_viewport_rect = !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) || (g.IO.MouseHoveredViewport != window->ViewportId) || !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration);
5910
3.00k
    if (clip_with_viewport_rect)
5911
3.00k
        window->ClipRect = window->Viewport->GetMainRect();
5912
5913
    // Resize grips and borders are on layer 1
5914
3.00k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
5915
5916
    // Manual resize grips
5917
3.00k
    PushID("#RESIZE");
5918
6.00k
    for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
5919
3.00k
    {
5920
3.00k
        const ImGuiResizeGripDef& def = resize_grip_def[resize_grip_n];
5921
3.00k
        const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, def.CornerPosN);
5922
5923
        // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
5924
3.00k
        bool hovered, held;
5925
3.00k
        ImRect resize_rect(corner - def.InnerDir * grip_hover_outer_size, corner + def.InnerDir * grip_hover_inner_size);
5926
3.00k
        if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
5927
3.00k
        if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
5928
3.00k
        ImGuiID resize_grip_id = window->GetID(resize_grip_n); // == GetWindowResizeCornerID()
5929
3.00k
        ItemAdd(resize_rect, resize_grip_id, NULL, ImGuiItemFlags_NoNav);
5930
3.00k
        ButtonBehavior(resize_rect, resize_grip_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
5931
        //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
5932
3.00k
        if (hovered || held)
5933
0
            g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
5934
5935
3.00k
        if (held && g.IO.MouseClickedCount[0] == 2 && resize_grip_n == 0)
5936
0
        {
5937
            // Manual auto-fit when double-clicking
5938
0
            size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit);
5939
0
            ret_auto_fit = true;
5940
0
            ClearActiveID();
5941
0
        }
5942
3.00k
        else if (held)
5943
0
        {
5944
            // Resize from any of the four corners
5945
            // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
5946
0
            ImVec2 clamp_min = ImVec2(def.CornerPosN.x == 1.0f ? visibility_rect.Min.x : -FLT_MAX, def.CornerPosN.y == 1.0f ? visibility_rect.Min.y : -FLT_MAX);
5947
0
            ImVec2 clamp_max = ImVec2(def.CornerPosN.x == 0.0f ? visibility_rect.Max.x : +FLT_MAX, def.CornerPosN.y == 0.0f ? visibility_rect.Max.y : +FLT_MAX);
5948
0
            ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(def.InnerDir * grip_hover_outer_size, def.InnerDir * -grip_hover_inner_size, def.CornerPosN); // Corner of the window corresponding to our corner grip
5949
0
            corner_target = ImClamp(corner_target, clamp_min, clamp_max);
5950
0
            CalcResizePosSizeFromAnyCorner(window, corner_target, def.CornerPosN, &pos_target, &size_target);
5951
0
        }
5952
5953
        // Only lower-left grip is visible before hovering/activating
5954
3.00k
        if (resize_grip_n == 0 || held || hovered)
5955
3.00k
            resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
5956
3.00k
    }
5957
3.00k
    for (int border_n = 0; border_n < resize_border_count; border_n++)
5958
0
    {
5959
0
        const ImGuiResizeBorderDef& def = resize_border_def[border_n];
5960
0
        const ImGuiAxis axis = (border_n == ImGuiDir_Left || border_n == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
5961
5962
0
        bool hovered, held;
5963
0
        ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
5964
0
        ImGuiID border_id = window->GetID(border_n + 4); // == GetWindowResizeBorderID()
5965
0
        ItemAdd(border_rect, border_id, NULL, ImGuiItemFlags_NoNav);
5966
0
        ButtonBehavior(border_rect, border_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
5967
        //GetForegroundDrawLists(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
5968
0
        if ((hovered && g.HoveredIdTimer > WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER) || held)
5969
0
        {
5970
0
            g.MouseCursor = (axis == ImGuiAxis_X) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
5971
0
            if (held)
5972
0
                *border_held = border_n;
5973
0
        }
5974
0
        if (held)
5975
0
        {
5976
0
            ImVec2 clamp_min(border_n == ImGuiDir_Right ? visibility_rect.Min.x : -FLT_MAX, border_n == ImGuiDir_Down ? visibility_rect.Min.y : -FLT_MAX);
5977
0
            ImVec2 clamp_max(border_n == ImGuiDir_Left  ? visibility_rect.Max.x : +FLT_MAX, border_n == ImGuiDir_Up   ? visibility_rect.Max.y : +FLT_MAX);
5978
0
            ImVec2 border_target = window->Pos;
5979
0
            border_target[axis] = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + WINDOWS_HOVER_PADDING;
5980
0
            border_target = ImClamp(border_target, clamp_min, clamp_max);
5981
0
            CalcResizePosSizeFromAnyCorner(window, border_target, ImMin(def.SegmentN1, def.SegmentN2), &pos_target, &size_target);
5982
0
        }
5983
0
    }
5984
3.00k
    PopID();
5985
5986
    // Restore nav layer
5987
3.00k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
5988
5989
    // Navigation resize (keyboard/gamepad)
5990
    // FIXME: This cannot be moved to NavUpdateWindowing() because CalcWindowSizeAfterConstraint() need to callback into user.
5991
    // Not even sure the callback works here.
5992
3.00k
    if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindowDockTree == window)
5993
0
    {
5994
0
        ImVec2 nav_resize_dir;
5995
0
        if (g.NavInputSource == ImGuiInputSource_Keyboard && g.IO.KeyShift)
5996
0
            nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
5997
0
        if (g.NavInputSource == ImGuiInputSource_Gamepad)
5998
0
            nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown);
5999
0
        if (nav_resize_dir.x != 0.0f || nav_resize_dir.y != 0.0f)
6000
0
        {
6001
0
            const float NAV_RESIZE_SPEED = 600.0f;
6002
0
            const float resize_step = NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y);
6003
0
            g.NavWindowingAccumDeltaSize += nav_resize_dir * resize_step;
6004
0
            g.NavWindowingAccumDeltaSize = ImMax(g.NavWindowingAccumDeltaSize, visibility_rect.Min - window->Pos - window->Size); // We need Pos+Size >= visibility_rect.Min, so Size >= visibility_rect.Min - Pos, so size_delta >= visibility_rect.Min - window->Pos - window->Size
6005
0
            g.NavWindowingToggleLayer = false;
6006
0
            g.NavDisableMouseHover = true;
6007
0
            resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
6008
0
            ImVec2 accum_floored = ImFloor(g.NavWindowingAccumDeltaSize);
6009
0
            if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
6010
0
            {
6011
                // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
6012
0
                size_target = CalcWindowSizeAfterConstraint(window, window->SizeFull + accum_floored);
6013
0
                g.NavWindowingAccumDeltaSize -= accum_floored;
6014
0
            }
6015
0
        }
6016
0
    }
6017
6018
    // Apply back modified position/size to window
6019
3.00k
    if (size_target.x != FLT_MAX)
6020
0
    {
6021
0
        window->SizeFull = size_target;
6022
0
        MarkIniSettingsDirty(window);
6023
0
    }
6024
3.00k
    if (pos_target.x != FLT_MAX)
6025
0
    {
6026
0
        window->Pos = ImFloor(pos_target);
6027
0
        MarkIniSettingsDirty(window);
6028
0
    }
6029
6030
3.00k
    window->Size = window->SizeFull;
6031
3.00k
    return ret_auto_fit;
6032
6.00k
}
6033
6034
static inline void ClampWindowPos(ImGuiWindow* window, const ImRect& visibility_rect)
6035
6.00k
{
6036
6.00k
    ImGuiContext& g = *GImGui;
6037
6.00k
    ImVec2 size_for_clamping = window->Size;
6038
6.00k
    if (g.IO.ConfigWindowsMoveFromTitleBarOnly && (!(window->Flags & ImGuiWindowFlags_NoTitleBar) || window->DockNodeAsHost))
6039
0
        size_for_clamping.y = ImGui::GetFrameHeight(); // Not using window->TitleBarHeight() as DockNodeAsHost will report 0.0f here.
6040
6.00k
    window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max);
6041
6.00k
}
6042
6043
static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
6044
9.00k
{
6045
9.00k
    ImGuiContext& g = *GImGui;
6046
9.00k
    float rounding = window->WindowRounding;
6047
9.00k
    float border_size = window->WindowBorderSize;
6048
9.00k
    if (border_size > 0.0f && !(window->Flags & ImGuiWindowFlags_NoBackground))
6049
6.98k
        window->DrawList->AddRect(window->Pos, window->Pos + window->Size, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
6050
6051
9.00k
    int border_held = window->ResizeBorderHeld;
6052
9.00k
    if (border_held != -1)
6053
0
    {
6054
0
        const ImGuiResizeBorderDef& def = resize_border_def[border_held];
6055
0
        ImRect border_r = GetResizeBorderRect(window, border_held, rounding, 0.0f);
6056
0
        window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI * 0.25f, def.OuterAngle);
6057
0
        window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI * 0.25f);
6058
0
        window->DrawList->PathStroke(GetColorU32(ImGuiCol_SeparatorActive), 0, ImMax(2.0f, border_size)); // Thicker than usual
6059
0
    }
6060
9.00k
    if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6061
0
    {
6062
0
        float y = window->Pos.y + window->TitleBarHeight() - 1;
6063
0
        window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), GetColorU32(ImGuiCol_Border), g.Style.FrameBorderSize);
6064
0
    }
6065
9.00k
}
6066
6067
// Draw background and borders
6068
// Draw and handle scrollbars
6069
void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size)
6070
9.00k
{
6071
9.00k
    ImGuiContext& g = *GImGui;
6072
9.00k
    ImGuiStyle& style = g.Style;
6073
9.00k
    ImGuiWindowFlags flags = window->Flags;
6074
6075
    // Ensure that ScrollBar doesn't read last frame's SkipItems
6076
9.00k
    IM_ASSERT(window->BeginCount == 0);
6077
9.00k
    window->SkipItems = false;
6078
6079
    // Draw window + handle manual resize
6080
    // As we highlight the title bar when want_focus is set, multiple reappearing windows will have their title bar highlighted on their reappearing frame.
6081
9.00k
    const float window_rounding = window->WindowRounding;
6082
9.00k
    const float window_border_size = window->WindowBorderSize;
6083
9.00k
    if (window->Collapsed)
6084
0
    {
6085
        // Title bar only
6086
0
        const float backup_border_size = style.FrameBorderSize;
6087
0
        g.Style.FrameBorderSize = window->WindowBorderSize;
6088
0
        ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
6089
0
        if (window->ViewportOwned)
6090
0
            title_bar_col |= IM_COL32_A_MASK; // No alpha (we don't support is_docking_transparent_payload here because simpler and less meaningful, but could with a bit of code shuffle/reuse)
6091
0
        RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
6092
0
        g.Style.FrameBorderSize = backup_border_size;
6093
0
    }
6094
9.00k
    else
6095
9.00k
    {
6096
        // Window background
6097
9.00k
        if (!(flags & ImGuiWindowFlags_NoBackground))
6098
9.00k
        {
6099
9.00k
            bool is_docking_transparent_payload = false;
6100
9.00k
            if (g.DragDropActive && (g.FrameCount - g.DragDropAcceptFrameCount) <= 1 && g.IO.ConfigDockingTransparentPayload)
6101
0
                if (g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && *(ImGuiWindow**)g.DragDropPayload.Data == window)
6102
0
                    is_docking_transparent_payload = true;
6103
6104
9.00k
            ImU32 bg_col = GetColorU32(GetWindowBgColorIdx(window));
6105
9.00k
            if (window->ViewportOwned)
6106
0
            {
6107
0
                bg_col |= IM_COL32_A_MASK; // No alpha
6108
0
                if (is_docking_transparent_payload)
6109
0
                    window->Viewport->Alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA;
6110
0
            }
6111
9.00k
            else
6112
9.00k
            {
6113
                // Adjust alpha. For docking
6114
9.00k
                bool override_alpha = false;
6115
9.00k
                float alpha = 1.0f;
6116
9.00k
                if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha)
6117
0
                {
6118
0
                    alpha = g.NextWindowData.BgAlphaVal;
6119
0
                    override_alpha = true;
6120
0
                }
6121
9.00k
                if (is_docking_transparent_payload)
6122
0
                {
6123
0
                    alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA; // FIXME-DOCK: Should that be an override?
6124
0
                    override_alpha = true;
6125
0
                }
6126
9.00k
                if (override_alpha)
6127
0
                    bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
6128
9.00k
            }
6129
6130
            // Render, for docked windows and host windows we ensure bg goes before decorations
6131
9.00k
            if (window->DockIsActive)
6132
0
                window->DockNode->LastBgColor = bg_col;
6133
9.00k
            ImDrawList* bg_draw_list = window->DockIsActive ? window->DockNode->HostWindow->DrawList : window->DrawList;
6134
9.00k
            if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6135
0
                bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
6136
9.00k
            bg_draw_list->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? 0 : ImDrawFlags_RoundCornersBottom);
6137
9.00k
            if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6138
0
                bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
6139
9.00k
        }
6140
9.00k
        if (window->DockIsActive)
6141
0
            window->DockNode->IsBgDrawnThisFrame = true;
6142
6143
        // Title bar
6144
        // (when docked, DockNode are drawing their own title bar. Individual windows however do NOT set the _NoTitleBar flag,
6145
        // in order for their pos/size to be matching their undocking state.)
6146
9.00k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6147
6.00k
        {
6148
6.00k
            ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
6149
6.00k
            window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags_RoundCornersTop);
6150
6.00k
        }
6151
6152
        // Menu bar
6153
9.00k
        if (flags & ImGuiWindowFlags_MenuBar)
6154
0
        {
6155
0
            ImRect menu_bar_rect = window->MenuBarRect();
6156
0
            menu_bar_rect.ClipWith(window->Rect());  // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them.
6157
0
            window->DrawList->AddRectFilled(menu_bar_rect.Min + ImVec2(window_border_size, 0), menu_bar_rect.Max - ImVec2(window_border_size, 0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundCornersTop);
6158
0
            if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
6159
0
                window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
6160
0
        }
6161
6162
        // Docking: Unhide tab bar (small triangle in the corner), drag from small triangle to quickly undock
6163
9.00k
        ImGuiDockNode* node = window->DockNode;
6164
9.00k
        if (window->DockIsActive && node->IsHiddenTabBar() && !node->IsNoTabBar())
6165
0
        {
6166
0
            float unhide_sz_draw = ImFloor(g.FontSize * 0.70f);
6167
0
            float unhide_sz_hit = ImFloor(g.FontSize * 0.55f);
6168
0
            ImVec2 p = node->Pos;
6169
0
            ImRect r(p, p + ImVec2(unhide_sz_hit, unhide_sz_hit));
6170
0
            ImGuiID unhide_id = window->GetID("#UNHIDE");
6171
0
            KeepAliveID(unhide_id);
6172
0
            bool hovered, held;
6173
0
            if (ButtonBehavior(r, unhide_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren))
6174
0
                node->WantHiddenTabBarToggle = true;
6175
0
            else if (held && IsMouseDragging(0))
6176
0
                StartMouseMovingWindowOrNode(window, node, true);
6177
6178
            // FIXME-DOCK: Ideally we'd use ImGuiCol_TitleBgActive/ImGuiCol_TitleBg here, but neither is guaranteed to be visible enough at this sort of size..
6179
0
            ImU32 col = GetColorU32(((held && hovered) || (node->IsFocused && !hovered)) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
6180
0
            window->DrawList->AddTriangleFilled(p, p + ImVec2(unhide_sz_draw, 0.0f), p + ImVec2(0.0f, unhide_sz_draw), col);
6181
0
        }
6182
6183
        // Scrollbars
6184
9.00k
        if (window->ScrollbarX)
6185
3.00k
            Scrollbar(ImGuiAxis_X);
6186
9.00k
        if (window->ScrollbarY)
6187
3.14k
            Scrollbar(ImGuiAxis_Y);
6188
6189
        // Render resize grips (after their input handling so we don't have a frame of latency)
6190
9.00k
        if (handle_borders_and_resize_grips && !(flags & ImGuiWindowFlags_NoResize))
6191
6.00k
        {
6192
12.0k
            for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6193
6.00k
            {
6194
6.00k
                const ImU32 col = resize_grip_col[resize_grip_n];
6195
6.00k
                if ((col & IM_COL32_A_MASK) == 0)
6196
3.00k
                    continue;
6197
3.00k
                const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
6198
3.00k
                const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
6199
3.00k
                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, window_border_size)));
6200
3.00k
                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, window_border_size) : ImVec2(window_border_size, resize_grip_draw_size)));
6201
3.00k
                window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12);
6202
3.00k
                window->DrawList->PathFillConvex(col);
6203
3.00k
            }
6204
6.00k
        }
6205
6206
        // Borders (for dock node host they will be rendered over after the tab bar)
6207
9.00k
        if (handle_borders_and_resize_grips && !window->DockNodeAsHost)
6208
9.00k
            RenderWindowOuterBorders(window);
6209
9.00k
    }
6210
9.00k
}
6211
6212
// When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead.
6213
// Render title text, collapse button, close button
6214
void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
6215
6.00k
{
6216
6.00k
    ImGuiContext& g = *GImGui;
6217
6.00k
    ImGuiStyle& style = g.Style;
6218
6.00k
    ImGuiWindowFlags flags = window->Flags;
6219
6220
6.00k
    const bool has_close_button = (p_open != NULL);
6221
6.00k
    const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);
6222
6223
    // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
6224
    // FIXME-NAV: Might want (or not?) to set the equivalent of ImGuiButtonFlags_NoNavFocus so that mouse clicks on standard title bar items don't necessarily set nav/keyboard ref?
6225
6.00k
    const ImGuiItemFlags item_flags_backup = g.CurrentItemFlags;
6226
6.00k
    g.CurrentItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
6227
6.00k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6228
6229
    // Layout buttons
6230
    // FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
6231
6.00k
    float pad_l = style.FramePadding.x;
6232
6.00k
    float pad_r = style.FramePadding.x;
6233
6.00k
    float button_sz = g.FontSize;
6234
6.00k
    ImVec2 close_button_pos;
6235
6.00k
    ImVec2 collapse_button_pos;
6236
6.00k
    if (has_close_button)
6237
0
    {
6238
0
        pad_r += button_sz;
6239
0
        close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);
6240
0
    }
6241
6.00k
    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
6242
0
    {
6243
0
        pad_r += button_sz;
6244
0
        collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);
6245
0
    }
6246
6.00k
    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
6247
6.00k
    {
6248
6.00k
        collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l - style.FramePadding.x, title_bar_rect.Min.y);
6249
6.00k
        pad_l += button_sz;
6250
6.00k
    }
6251
6252
    // Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
6253
6.00k
    if (has_collapse_button)
6254
6.00k
        if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos, NULL))
6255
0
            window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
6256
6257
    // Close button
6258
6.00k
    if (has_close_button)
6259
0
        if (CloseButton(window->GetID("#CLOSE"), close_button_pos))
6260
0
            *p_open = false;
6261
6262
6.00k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6263
6.00k
    g.CurrentItemFlags = item_flags_backup;
6264
6265
    // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
6266
    // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
6267
6.00k
    const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? button_sz * 0.80f : 0.0f;
6268
6.00k
    const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
6269
6270
    // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
6271
    // while uncentered title text will still reach edges correctly.
6272
6.00k
    if (pad_l > style.FramePadding.x)
6273
6.00k
        pad_l += g.Style.ItemInnerSpacing.x;
6274
6.00k
    if (pad_r > style.FramePadding.x)
6275
0
        pad_r += g.Style.ItemInnerSpacing.x;
6276
6.00k
    if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
6277
0
    {
6278
0
        float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
6279
0
        float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
6280
0
        pad_l = ImMax(pad_l, pad_extend * centerness);
6281
0
        pad_r = ImMax(pad_r, pad_extend * centerness);
6282
0
    }
6283
6284
6.00k
    ImRect layout_r(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y);
6285
6.00k
    ImRect clip_r(layout_r.Min.x, layout_r.Min.y, ImMin(layout_r.Max.x + g.Style.ItemInnerSpacing.x, title_bar_rect.Max.x), layout_r.Max.y);
6286
6.00k
    if (flags & ImGuiWindowFlags_UnsavedDocument)
6287
0
    {
6288
0
        ImVec2 marker_pos;
6289
0
        marker_pos.x = ImClamp(layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x + text_size.x, layout_r.Min.x, layout_r.Max.x);
6290
0
        marker_pos.y = (layout_r.Min.y + layout_r.Max.y) * 0.5f;
6291
0
        if (marker_pos.x > layout_r.Min.x)
6292
0
        {
6293
0
            RenderBullet(window->DrawList, marker_pos, GetColorU32(ImGuiCol_Text));
6294
0
            clip_r.Max.x = ImMin(clip_r.Max.x, marker_pos.x - (int)(marker_size_x * 0.5f));
6295
0
        }
6296
0
    }
6297
    //if (g.IO.KeyShift) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6298
    //if (g.IO.KeyCtrl) window->DrawList->AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6299
6.00k
    RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r);
6300
6.00k
}
6301
6302
void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
6303
9.00k
{
6304
9.00k
    window->ParentWindow = parent_window;
6305
9.00k
    window->RootWindow = window->RootWindowPopupTree = window->RootWindowDockTree = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
6306
9.00k
    if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
6307
3.00k
    {
6308
3.00k
        window->RootWindowDockTree = parent_window->RootWindowDockTree;
6309
3.00k
        if (!window->DockIsActive && !(parent_window->Flags & ImGuiWindowFlags_DockNodeHost))
6310
3.00k
            window->RootWindow = parent_window->RootWindow;
6311
3.00k
    }
6312
9.00k
    if (parent_window && (flags & ImGuiWindowFlags_Popup))
6313
0
        window->RootWindowPopupTree = parent_window->RootWindowPopupTree;
6314
9.00k
    if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) // FIXME: simply use _NoTitleBar ?
6315
3.00k
        window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
6316
9.00k
    while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened)
6317
0
    {
6318
0
        IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
6319
0
        window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
6320
0
    }
6321
9.00k
}
6322
6323
// When a modal popup is open, newly created windows that want focus (i.e. are not popups and do not specify ImGuiWindowFlags_NoFocusOnAppearing)
6324
// should be positioned behind that modal window, unless the window was created inside the modal begin-stack.
6325
// In case of multiple stacked modals newly created window honors begin stack order and does not go below its own modal parent.
6326
// - Window             // FindBlockingModal() returns Modal1
6327
//   - Window           //                  .. returns Modal1
6328
//   - Modal1           //                  .. returns Modal2
6329
//      - Window        //                  .. returns Modal2
6330
//          - Window    //                  .. returns Modal2
6331
//          - Modal2    //                  .. returns Modal2
6332
static ImGuiWindow* ImGui::FindBlockingModal(ImGuiWindow* window)
6333
0
{
6334
0
    ImGuiContext& g = *GImGui;
6335
0
    if (g.OpenPopupStack.Size <= 0)
6336
0
        return NULL;
6337
6338
    // Find a modal that has common parent with specified window. Specified window should be positioned behind that modal.
6339
0
    for (int i = g.OpenPopupStack.Size - 1; i >= 0; i--)
6340
0
    {
6341
0
        ImGuiWindow* popup_window = g.OpenPopupStack.Data[i].Window;
6342
0
        if (popup_window == NULL || !(popup_window->Flags & ImGuiWindowFlags_Modal))
6343
0
            continue;
6344
0
        if (!popup_window->Active && !popup_window->WasActive)      // Check WasActive, because this code may run before popup renders on current frame, also check Active to handle newly created windows.
6345
0
            continue;
6346
0
        if (IsWindowWithinBeginStackOf(window, popup_window))       // Window is rendered over last modal, no render order change needed.
6347
0
            break;
6348
0
        for (ImGuiWindow* parent = popup_window->ParentWindowInBeginStack->RootWindow; parent != NULL; parent = parent->ParentWindowInBeginStack->RootWindow)
6349
0
            if (IsWindowWithinBeginStackOf(window, parent))
6350
0
                return popup_window;                                // Place window above its begin stack parent.
6351
0
    }
6352
0
    return NULL;
6353
0
}
6354
6355
// Push a new Dear ImGui window to add widgets to.
6356
// - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair.
6357
// - Begin/End can be called multiple times during the frame with the same window name to append content.
6358
// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
6359
//   You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file.
6360
// - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned.
6361
// - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed.
6362
bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
6363
9.00k
{
6364
9.00k
    ImGuiContext& g = *GImGui;
6365
9.00k
    const ImGuiStyle& style = g.Style;
6366
9.00k
    IM_ASSERT(name != NULL && name[0] != '\0');     // Window name required
6367
9.00k
    IM_ASSERT(g.WithinFrameScope);                  // Forgot to call ImGui::NewFrame()
6368
9.00k
    IM_ASSERT(g.FrameCountEnded != g.FrameCount);   // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
6369
6370
    // Find or create
6371
9.00k
    ImGuiWindow* window = FindWindowByName(name);
6372
9.00k
    const bool window_just_created = (window == NULL);
6373
9.00k
    if (window_just_created)
6374
3
        window = CreateNewWindow(name, flags);
6375
6376
    // Automatically disable manual moving/resizing when NoInputs is set
6377
9.00k
    if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
6378
0
        flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
6379
6380
9.00k
    if (flags & ImGuiWindowFlags_NavFlattened)
6381
9.00k
        IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow);
6382
6383
9.00k
    const int current_frame = g.FrameCount;
6384
9.00k
    const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
6385
9.00k
    window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
6386
6387
    // Update the Appearing flag (note: the BeginDocked() path may also set this to true later)
6388
9.00k
    bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
6389
9.00k
    if (flags & ImGuiWindowFlags_Popup)
6390
0
    {
6391
0
        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6392
0
        window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
6393
0
        window_just_activated_by_user |= (window != popup_ref.Window);
6394
0
    }
6395
6396
    // Update Flags, LastFrameActive, BeginOrderXXX fields
6397
9.00k
    const bool window_was_appearing = window->Appearing;
6398
9.00k
    if (first_begin_of_the_frame)
6399
9.00k
    {
6400
9.00k
        UpdateWindowInFocusOrderList(window, window_just_created, flags);
6401
9.00k
        window->Appearing = window_just_activated_by_user;
6402
9.00k
        if (window->Appearing)
6403
3
            SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
6404
9.00k
        window->FlagsPreviousFrame = window->Flags;
6405
9.00k
        window->Flags = (ImGuiWindowFlags)flags;
6406
9.00k
        window->LastFrameActive = current_frame;
6407
9.00k
        window->LastTimeActive = (float)g.Time;
6408
9.00k
        window->BeginOrderWithinParent = 0;
6409
9.00k
        window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
6410
9.00k
    }
6411
0
    else
6412
0
    {
6413
0
        flags = window->Flags;
6414
0
    }
6415
6416
    // Docking
6417
    // (NB: during the frame dock nodes are created, it is possible that (window->DockIsActive == false) even though (window->DockNode->Windows.Size > 1)
6418
9.00k
    IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL); // Cannot be both
6419
9.00k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasDock)
6420
0
        SetWindowDock(window, g.NextWindowData.DockId, g.NextWindowData.DockCond);
6421
9.00k
    if (first_begin_of_the_frame)
6422
9.00k
    {
6423
9.00k
        bool has_dock_node = (window->DockId != 0 || window->DockNode != NULL);
6424
9.00k
        bool new_auto_dock_node = !has_dock_node && GetWindowAlwaysWantOwnTabBar(window);
6425
9.00k
        bool dock_node_was_visible = window->DockNodeIsVisible;
6426
9.00k
        bool dock_tab_was_visible = window->DockTabIsVisible;
6427
9.00k
        if (has_dock_node || new_auto_dock_node)
6428
0
        {
6429
0
            BeginDocked(window, p_open);
6430
0
            flags = window->Flags;
6431
0
            if (window->DockIsActive)
6432
0
            {
6433
0
                IM_ASSERT(window->DockNode != NULL);
6434
0
                g.NextWindowData.Flags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint; // Docking currently override constraints
6435
0
            }
6436
6437
            // Amend the Appearing flag
6438
0
            if (window->DockTabIsVisible && !dock_tab_was_visible && dock_node_was_visible && !window->Appearing && !window_was_appearing)
6439
0
            {
6440
0
                window->Appearing = true;
6441
0
                SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
6442
0
            }
6443
0
        }
6444
9.00k
        else
6445
9.00k
        {
6446
9.00k
            window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
6447
9.00k
        }
6448
9.00k
    }
6449
6450
    // Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack
6451
9.00k
    ImGuiWindow* parent_window_in_stack = (window->DockIsActive && window->DockNode->HostWindow) ? window->DockNode->HostWindow : g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back().Window;
6452
9.00k
    ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
6453
9.00k
    IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
6454
6455
    // We allow window memory to be compacted so recreate the base stack when needed.
6456
9.00k
    if (window->IDStack.Size == 0)
6457
0
        window->IDStack.push_back(window->ID);
6458
6459
    // Add to stack
6460
    // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
6461
9.00k
    g.CurrentWindow = window;
6462
9.00k
    ImGuiWindowStackData window_stack_data;
6463
9.00k
    window_stack_data.Window = window;
6464
9.00k
    window_stack_data.ParentLastItemDataBackup = g.LastItemData;
6465
9.00k
    window_stack_data.StackSizesOnBegin.SetToCurrentState();
6466
9.00k
    g.CurrentWindowStack.push_back(window_stack_data);
6467
9.00k
    if (flags & ImGuiWindowFlags_ChildMenu)
6468
0
        g.BeginMenuCount++;
6469
6470
    // Update ->RootWindow and others pointers (before any possible call to FocusWindow)
6471
9.00k
    if (first_begin_of_the_frame)
6472
9.00k
    {
6473
9.00k
        UpdateWindowParentAndRootLinks(window, flags, parent_window);
6474
9.00k
        window->ParentWindowInBeginStack = parent_window_in_stack;
6475
9.00k
    }
6476
6477
    // Add to focus scope stack
6478
9.00k
    PushFocusScope(window->ID);
6479
9.00k
    window->NavRootFocusScopeId = g.CurrentFocusScopeId;
6480
9.00k
    g.CurrentWindow = NULL;
6481
6482
    // Add to popup stack
6483
9.00k
    if (flags & ImGuiWindowFlags_Popup)
6484
0
    {
6485
0
        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6486
0
        popup_ref.Window = window;
6487
0
        popup_ref.ParentNavLayer = parent_window_in_stack->DC.NavLayerCurrent;
6488
0
        g.BeginPopupStack.push_back(popup_ref);
6489
0
        window->PopupId = popup_ref.PopupId;
6490
0
    }
6491
6492
    // Process SetNextWindow***() calls
6493
    // (FIXME: Consider splitting the HasXXX flags into X/Y components
6494
9.00k
    bool window_pos_set_by_api = false;
6495
9.00k
    bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
6496
9.00k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos)
6497
0
    {
6498
0
        window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
6499
0
        if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
6500
0
        {
6501
            // May be processed on the next frame if this is our first frame and we are measuring size
6502
            // FIXME: Look into removing the branch so everything can go through this same code path for consistency.
6503
0
            window->SetWindowPosVal = g.NextWindowData.PosVal;
6504
0
            window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
6505
0
            window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
6506
0
        }
6507
0
        else
6508
0
        {
6509
0
            SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
6510
0
        }
6511
0
    }
6512
9.00k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)
6513
6.00k
    {
6514
6.00k
        window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
6515
6.00k
        window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
6516
6.00k
        SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
6517
6.00k
    }
6518
9.00k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasScroll)
6519
0
    {
6520
0
        if (g.NextWindowData.ScrollVal.x >= 0.0f)
6521
0
        {
6522
0
            window->ScrollTarget.x = g.NextWindowData.ScrollVal.x;
6523
0
            window->ScrollTargetCenterRatio.x = 0.0f;
6524
0
        }
6525
0
        if (g.NextWindowData.ScrollVal.y >= 0.0f)
6526
0
        {
6527
0
            window->ScrollTarget.y = g.NextWindowData.ScrollVal.y;
6528
0
            window->ScrollTargetCenterRatio.y = 0.0f;
6529
0
        }
6530
0
    }
6531
9.00k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize)
6532
0
        window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
6533
9.00k
    else if (first_begin_of_the_frame)
6534
9.00k
        window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
6535
9.00k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasWindowClass)
6536
0
        window->WindowClass = g.NextWindowData.WindowClass;
6537
9.00k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed)
6538
0
        SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
6539
9.00k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus)
6540
0
        FocusWindow(window);
6541
9.00k
    if (window->Appearing)
6542
3
        SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
6543
6544
    // When reusing window again multiple times a frame, just append content (don't need to setup again)
6545
9.00k
    if (first_begin_of_the_frame)
6546
9.00k
    {
6547
        // Initialize
6548
9.00k
        const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
6549
9.00k
        const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
6550
9.00k
        window->Active = true;
6551
9.00k
        window->HasCloseButton = (p_open != NULL);
6552
9.00k
        window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);
6553
9.00k
        window->IDStack.resize(1);
6554
9.00k
        window->DrawList->_ResetForNewFrame();
6555
9.00k
        window->DC.CurrentTableIdx = -1;
6556
9.00k
        if (flags & ImGuiWindowFlags_DockNodeHost)
6557
0
        {
6558
0
            window->DrawList->ChannelsSplit(2);
6559
0
            window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG); // Render decorations on channel 1 as we will render the backgrounds manually later
6560
0
        }
6561
6562
        // Restore buffer capacity when woken from a compacted state, to avoid
6563
9.00k
        if (window->MemoryCompacted)
6564
0
            GcAwakeTransientWindowBuffers(window);
6565
6566
        // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
6567
        // The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere.
6568
9.00k
        bool window_title_visible_elsewhere = false;
6569
9.00k
        if ((window->Viewport && window->Viewport->Window == window) || (window->DockIsActive))
6570
0
            window_title_visible_elsewhere = true;
6571
9.00k
        else if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0)   // Window titles visible when using CTRL+TAB
6572
0
            window_title_visible_elsewhere = true;
6573
9.00k
        if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
6574
0
        {
6575
0
            size_t buf_len = (size_t)window->NameBufLen;
6576
0
            window->Name = ImStrdupcpy(window->Name, &buf_len, name);
6577
0
            window->NameBufLen = (int)buf_len;
6578
0
        }
6579
6580
        // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
6581
6582
        // Update contents size from last frame for auto-fitting (or use explicit size)
6583
9.00k
        CalcWindowContentSizes(window, &window->ContentSize, &window->ContentSizeIdeal);
6584
6585
        // FIXME: These flags are decremented before they are used. This means that in order to have these fields produce their intended behaviors
6586
        // for one frame we must set them to at least 2, which is counter-intuitive. HiddenFramesCannotSkipItems is a more complicated case because
6587
        // it has a single usage before this code block and may be set below before it is finally checked.
6588
9.00k
        if (window->HiddenFramesCanSkipItems > 0)
6589
0
            window->HiddenFramesCanSkipItems--;
6590
9.00k
        if (window->HiddenFramesCannotSkipItems > 0)
6591
2
            window->HiddenFramesCannotSkipItems--;
6592
9.00k
        if (window->HiddenFramesForRenderOnly > 0)
6593
0
            window->HiddenFramesForRenderOnly--;
6594
6595
        // Hide new windows for one frame until they calculate their size
6596
9.00k
        if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
6597
1
            window->HiddenFramesCannotSkipItems = 1;
6598
6599
        // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
6600
        // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
6601
9.00k
        if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
6602
0
        {
6603
0
            window->HiddenFramesCannotSkipItems = 1;
6604
0
            if (flags & ImGuiWindowFlags_AlwaysAutoResize)
6605
0
            {
6606
0
                if (!window_size_x_set_by_api)
6607
0
                    window->Size.x = window->SizeFull.x = 0.f;
6608
0
                if (!window_size_y_set_by_api)
6609
0
                    window->Size.y = window->SizeFull.y = 0.f;
6610
0
                window->ContentSize = window->ContentSizeIdeal = ImVec2(0.f, 0.f);
6611
0
            }
6612
0
        }
6613
6614
        // SELECT VIEWPORT
6615
        // We need to do this before using any style/font sizes, as viewport with a different DPI may affect font sizes.
6616
6617
9.00k
        WindowSelectViewport(window);
6618
9.00k
        SetCurrentViewport(window, window->Viewport);
6619
9.00k
        window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
6620
9.00k
        SetCurrentWindow(window);
6621
9.00k
        flags = window->Flags;
6622
6623
        // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
6624
        // We read Style data after the call to UpdateSelectWindowViewport() which might be swapping the style.
6625
6626
9.00k
        if (flags & ImGuiWindowFlags_ChildWindow)
6627
3.00k
            window->WindowBorderSize = style.ChildBorderSize;
6628
6.00k
        else
6629
6.00k
            window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
6630
9.00k
        if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_Popup)) && window->WindowBorderSize == 0.0f)
6631
2.02k
            window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
6632
6.98k
        else
6633
6.98k
            window->WindowPadding = style.WindowPadding;
6634
6635
        // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size.
6636
9.00k
        window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
6637
9.00k
        window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
6638
6639
9.00k
        bool use_current_size_for_scrollbar_x = window_just_created;
6640
9.00k
        bool use_current_size_for_scrollbar_y = window_just_created;
6641
6642
        // Collapse window by double-clicking on title bar
6643
        // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing
6644
9.00k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse) && !window->DockIsActive)
6645
6.00k
        {
6646
            // We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), so verify that we don't have items over the title bar.
6647
6.00k
            ImRect title_bar_rect = window->TitleBarRect();
6648
6.00k
            if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseClickedCount[0] == 2)
6649
0
                window->WantCollapseToggle = true;
6650
6.00k
            if (window->WantCollapseToggle)
6651
0
            {
6652
0
                window->Collapsed = !window->Collapsed;
6653
0
                if (!window->Collapsed)
6654
0
                    use_current_size_for_scrollbar_y = true;
6655
0
                MarkIniSettingsDirty(window);
6656
0
            }
6657
6.00k
        }
6658
3.00k
        else
6659
3.00k
        {
6660
3.00k
            window->Collapsed = false;
6661
3.00k
        }
6662
9.00k
        window->WantCollapseToggle = false;
6663
6664
        // SIZE
6665
6666
        // Outer Decoration Sizes
6667
        // (we need to clear ScrollbarSize immediatly as CalcWindowAutoFitSize() needs it and can be called from other locations).
6668
9.00k
        const ImVec2 scrollbar_sizes_from_last_frame = window->ScrollbarSizes;
6669
9.00k
        window->DecoOuterSizeX1 = 0.0f;
6670
9.00k
        window->DecoOuterSizeX2 = 0.0f;
6671
9.00k
        window->DecoOuterSizeY1 = window->TitleBarHeight() + window->MenuBarHeight();
6672
9.00k
        window->DecoOuterSizeY2 = 0.0f;
6673
9.00k
        window->ScrollbarSizes = ImVec2(0.0f, 0.0f);
6674
6675
        // Calculate auto-fit size, handle automatic resize
6676
9.00k
        const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal);
6677
9.00k
        if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
6678
0
        {
6679
            // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
6680
0
            if (!window_size_x_set_by_api)
6681
0
            {
6682
0
                window->SizeFull.x = size_auto_fit.x;
6683
0
                use_current_size_for_scrollbar_x = true;
6684
0
            }
6685
0
            if (!window_size_y_set_by_api)
6686
0
            {
6687
0
                window->SizeFull.y = size_auto_fit.y;
6688
0
                use_current_size_for_scrollbar_y = true;
6689
0
            }
6690
0
        }
6691
9.00k
        else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
6692
2
        {
6693
            // Auto-fit may only grow window during the first few frames
6694
            // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
6695
2
            if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
6696
2
            {
6697
2
                window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
6698
2
                use_current_size_for_scrollbar_x = true;
6699
2
            }
6700
2
            if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
6701
2
            {
6702
2
                window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
6703
2
                use_current_size_for_scrollbar_y = true;
6704
2
            }
6705
2
            if (!window->Collapsed)
6706
2
                MarkIniSettingsDirty(window);
6707
2
        }
6708
6709
        // Apply minimum/maximum window size constraints and final size
6710
9.00k
        window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull);
6711
9.00k
        window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
6712
6713
        // POSITION
6714
6715
        // Popup latch its initial position, will position itself when it appears next frame
6716
9.00k
        if (window_just_activated_by_user)
6717
3
        {
6718
3
            window->AutoPosLastDirection = ImGuiDir_None;
6719
3
            if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos()
6720
0
                window->Pos = g.BeginPopupStack.back().OpenPopupPos;
6721
3
        }
6722
6723
        // Position child window
6724
9.00k
        if (flags & ImGuiWindowFlags_ChildWindow)
6725
3.00k
        {
6726
3.00k
            IM_ASSERT(parent_window && parent_window->Active);
6727
3.00k
            window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
6728
3.00k
            parent_window->DC.ChildWindows.push_back(window);
6729
3.00k
            if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
6730
3.00k
                window->Pos = parent_window->DC.CursorPos;
6731
3.00k
        }
6732
6733
9.00k
        const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
6734
9.00k
        if (window_pos_with_pivot)
6735
0
            SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering)
6736
9.00k
        else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
6737
0
            window->Pos = FindBestWindowPosForPopup(window);
6738
9.00k
        else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
6739
0
            window->Pos = FindBestWindowPosForPopup(window);
6740
9.00k
        else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
6741
0
            window->Pos = FindBestWindowPosForPopup(window);
6742
6743
        // Late create viewport if we don't fit within our current host viewport.
6744
9.00k
        if (window->ViewportAllowPlatformMonitorExtend >= 0 && !window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_Minimized))
6745
0
            if (!window->Viewport->GetMainRect().Contains(window->Rect()))
6746
0
            {
6747
                // This is based on the assumption that the DPI will be known ahead (same as the DPI of the selection done in UpdateSelectWindowViewport)
6748
                //ImGuiViewport* old_viewport = window->Viewport;
6749
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
6750
6751
                // FIXME-DPI
6752
                //IM_ASSERT(old_viewport->DpiScale == window->Viewport->DpiScale); // FIXME-DPI: Something went wrong
6753
0
                SetCurrentViewport(window, window->Viewport);
6754
0
                window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
6755
0
                SetCurrentWindow(window);
6756
0
            }
6757
6758
9.00k
        if (window->ViewportOwned)
6759
0
            WindowSyncOwnedViewport(window, parent_window_in_stack);
6760
6761
        // Calculate the range of allowed position for that window (to be movable and visible past safe area padding)
6762
        // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect.
6763
9.00k
        ImRect viewport_rect(window->Viewport->GetMainRect());
6764
9.00k
        ImRect viewport_work_rect(window->Viewport->GetWorkRect());
6765
9.00k
        ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
6766
9.00k
        ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding);
6767
6768
        // Clamp position/size so window stays visible within its viewport or monitor
6769
        // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
6770
        // FIXME: Similar to code in GetWindowAllowedExtentRect()
6771
9.00k
        if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow))
6772
6.00k
        {
6773
6.00k
            if (!window->ViewportOwned && viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f)
6774
6.00k
            {
6775
6.00k
                ClampWindowPos(window, visibility_rect);
6776
6.00k
            }
6777
0
            else if (window->ViewportOwned && g.PlatformIO.Monitors.Size > 0)
6778
0
            {
6779
                // Lost windows (e.g. a monitor disconnected) will naturally moved to the fallback/dummy monitor aka the main viewport.
6780
0
                const ImGuiPlatformMonitor* monitor = GetViewportPlatformMonitor(window->Viewport);
6781
0
                visibility_rect.Min = monitor->WorkPos + visibility_padding;
6782
0
                visibility_rect.Max = monitor->WorkPos + monitor->WorkSize - visibility_padding;
6783
0
                ClampWindowPos(window, visibility_rect);
6784
0
            }
6785
6.00k
        }
6786
9.00k
        window->Pos = ImFloor(window->Pos);
6787
6788
        // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
6789
        // Large values tend to lead to variety of artifacts and are not recommended.
6790
9.00k
        if (window->ViewportOwned || window->DockIsActive)
6791
0
            window->WindowRounding = 0.0f;
6792
9.00k
        else
6793
9.00k
            window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
6794
6795
        // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts.
6796
        //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar))
6797
        //    window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f);
6798
6799
        // Apply window focus (new and reactivated windows are moved to front)
6800
9.00k
        bool want_focus = false;
6801
9.00k
        if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
6802
3
        {
6803
3
            if (flags & ImGuiWindowFlags_Popup)
6804
0
                want_focus = true;
6805
3
            else if ((window->DockIsActive || (flags & ImGuiWindowFlags_ChildWindow) == 0) && !(flags & ImGuiWindowFlags_Tooltip))
6806
2
                want_focus = true;
6807
6808
3
            ImGuiWindow* modal = GetTopMostPopupModal();
6809
3
            if (modal != NULL && !IsWindowWithinBeginStackOf(window, modal))
6810
0
            {
6811
                // Avoid focusing a window that is created outside of active modal. This will prevent active modal from being closed.
6812
                // Since window is not focused it would reappear at the same display position like the last time it was visible.
6813
                // In case of completely new windows it would go to the top (over current modal), but input to such window would still be blocked by modal.
6814
                // Position window behind a modal that is not a begin-parent of this window.
6815
0
                want_focus = false;
6816
0
                if (window == window->RootWindow)
6817
0
                {
6818
0
                    ImGuiWindow* blocking_modal = FindBlockingModal(window);
6819
0
                    IM_ASSERT(blocking_modal != NULL);
6820
0
                    BringWindowToDisplayBehind(window, blocking_modal);
6821
0
                }
6822
0
            }
6823
3
        }
6824
6825
        // [Test Engine] Register whole window in the item system
6826
#ifdef IMGUI_ENABLE_TEST_ENGINE
6827
        if (g.TestEngineHookItems)
6828
        {
6829
            IM_ASSERT(window->IDStack.Size == 1);
6830
            window->IDStack.Size = 0; // As window->IDStack[0] == window->ID here, make sure TestEngine doesn't erroneously see window as parent of itself.
6831
            IMGUI_TEST_ENGINE_ITEM_ADD(window->Rect(), window->ID);
6832
            IMGUI_TEST_ENGINE_ITEM_INFO(window->ID, window->Name, (g.HoveredWindow == window) ? ImGuiItemStatusFlags_HoveredRect : 0);
6833
            window->IDStack.Size = 1;
6834
        }
6835
#endif
6836
6837
        // Decide if we are going to handle borders and resize grips
6838
9.00k
        const bool handle_borders_and_resize_grips = (window->DockNodeAsHost || !window->DockIsActive);
6839
6840
        // Handle manual resize: Resize Grips, Borders, Gamepad
6841
9.00k
        int border_held = -1;
6842
9.00k
        ImU32 resize_grip_col[4] = {};
6843
9.00k
        const int resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it.
6844
9.00k
        const float resize_grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
6845
9.00k
        if (handle_borders_and_resize_grips && !window->Collapsed)
6846
9.00k
            if (UpdateWindowManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect))
6847
0
                use_current_size_for_scrollbar_x = use_current_size_for_scrollbar_y = true;
6848
9.00k
        window->ResizeBorderHeld = (signed char)border_held;
6849
6850
        // Synchronize window --> viewport again and one last time (clamping and manual resize may have affected either)
6851
9.00k
        if (window->ViewportOwned)
6852
0
        {
6853
0
            if (!window->Viewport->PlatformRequestMove)
6854
0
                window->Viewport->Pos = window->Pos;
6855
0
            if (!window->Viewport->PlatformRequestResize)
6856
0
                window->Viewport->Size = window->Size;
6857
0
            window->Viewport->UpdateWorkRect();
6858
0
            viewport_rect = window->Viewport->GetMainRect();
6859
0
        }
6860
6861
        // Save last known viewport position within the window itself (so it can be saved in .ini file and restored)
6862
9.00k
        window->ViewportPos = window->Viewport->Pos;
6863
6864
        // SCROLLBAR VISIBILITY
6865
6866
        // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
6867
9.00k
        if (!window->Collapsed)
6868
9.00k
        {
6869
            // When reading the current size we need to read it after size constraints have been applied.
6870
            // Intentionally use previous frame values for InnerRect and ScrollbarSizes.
6871
            // And when we use window->DecorationUp here it doesn't have ScrollbarSizes.y applied yet.
6872
9.00k
            ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2));
6873
9.00k
            ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + scrollbar_sizes_from_last_frame;
6874
9.00k
            ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
6875
9.00k
            float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
6876
9.00k
            float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
6877
            //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
6878
9.00k
            window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
6879
9.00k
            window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
6880
9.00k
            if (window->ScrollbarX && !window->ScrollbarY)
6881
108
                window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar);
6882
9.00k
            window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
6883
6884
            // Amend the partially filled window->DecorationXXX values.
6885
9.00k
            window->DecoOuterSizeX2 += window->ScrollbarSizes.x;
6886
9.00k
            window->DecoOuterSizeY2 += window->ScrollbarSizes.y;
6887
9.00k
        }
6888
6889
        // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
6890
        // Update various regions. Variables they depend on should be set above in this function.
6891
        // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
6892
6893
        // Outer rectangle
6894
        // Not affected by window border size. Used by:
6895
        // - FindHoveredWindow() (w/ extra padding when border resize is enabled)
6896
        // - Begin() initial clipping rect for drawing window background and borders.
6897
        // - Begin() clipping whole child
6898
9.00k
        const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
6899
9.00k
        const ImRect outer_rect = window->Rect();
6900
9.00k
        const ImRect title_bar_rect = window->TitleBarRect();
6901
9.00k
        window->OuterRectClipped = outer_rect;
6902
9.00k
        if (window->DockIsActive)
6903
0
            window->OuterRectClipped.Min.y += window->TitleBarHeight();
6904
9.00k
        window->OuterRectClipped.ClipWith(host_rect);
6905
6906
        // Inner rectangle
6907
        // Not affected by window border size. Used by:
6908
        // - InnerClipRect
6909
        // - ScrollToRectEx()
6910
        // - NavUpdatePageUpPageDown()
6911
        // - Scrollbar()
6912
9.00k
        window->InnerRect.Min.x = window->Pos.x + window->DecoOuterSizeX1;
6913
9.00k
        window->InnerRect.Min.y = window->Pos.y + window->DecoOuterSizeY1;
6914
9.00k
        window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->DecoOuterSizeX2;
6915
9.00k
        window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->DecoOuterSizeY2;
6916
6917
        // Inner clipping rectangle.
6918
        // Will extend a little bit outside the normal work region.
6919
        // This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
6920
        // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
6921
        // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
6922
        // Affected by window/frame border size. Used by:
6923
        // - Begin() initial clip rect
6924
9.00k
        float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
6925
9.00k
        window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
6926
9.00k
        window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size);
6927
9.00k
        window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
6928
9.00k
        window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize);
6929
9.00k
        window->InnerClipRect.ClipWithFull(host_rect);
6930
6931
        // Default item width. Make it proportional to window size if window manually resizes
6932
9.00k
        if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
6933
9.00k
            window->ItemWidthDefault = ImFloor(window->Size.x * 0.65f);
6934
0
        else
6935
0
            window->ItemWidthDefault = ImFloor(g.FontSize * 16.0f);
6936
6937
        // SCROLLING
6938
6939
        // Lock down maximum scrolling
6940
        // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
6941
        // for right/bottom aligned items without creating a scrollbar.
6942
9.00k
        window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
6943
9.00k
        window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
6944
6945
        // Apply scrolling
6946
9.00k
        window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
6947
9.00k
        window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
6948
9.00k
        window->DecoInnerSizeX1 = window->DecoInnerSizeY1 = 0.0f;
6949
6950
        // DRAWING
6951
6952
        // Setup draw list and outer clipping rectangle
6953
9.00k
        IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0);
6954
9.00k
        window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
6955
9.00k
        PushClipRect(host_rect.Min, host_rect.Max, false);
6956
6957
        // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71)
6958
        // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
6959
        // FIXME: User code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected (github #4493)
6960
9.00k
        const bool is_undocked_or_docked_visible = !window->DockIsActive || window->DockTabIsVisible;
6961
9.00k
        if (is_undocked_or_docked_visible)
6962
9.00k
        {
6963
9.00k
            bool render_decorations_in_parent = false;
6964
9.00k
            if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
6965
3.00k
            {
6966
                // - We test overlap with the previous child window only (testing all would end up being O(log N) not a good investment here)
6967
                // - We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping childs
6968
3.00k
                ImGuiWindow* previous_child = parent_window->DC.ChildWindows.Size >= 2 ? parent_window->DC.ChildWindows[parent_window->DC.ChildWindows.Size - 2] : NULL;
6969
3.00k
                bool previous_child_overlapping = previous_child ? previous_child->Rect().Overlaps(window->Rect()) : false;
6970
3.00k
                bool parent_is_empty = parent_window->DrawList->VtxBuffer.Size > 0;
6971
3.00k
                if (window->DrawList->CmdBuffer.back().ElemCount == 0 && parent_is_empty && !previous_child_overlapping)
6972
3.00k
                    render_decorations_in_parent = true;
6973
3.00k
            }
6974
9.00k
            if (render_decorations_in_parent)
6975
3.00k
                window->DrawList = parent_window->DrawList;
6976
6977
            // Handle title bar, scrollbar, resize grips and resize borders
6978
9.00k
            const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
6979
9.00k
            const bool title_bar_is_highlight = want_focus || (window_to_highlight && (window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight || (window->DockNode && window->DockNode == window_to_highlight->DockNode)));
6980
9.00k
            RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_count, resize_grip_col, resize_grip_draw_size);
6981
6982
9.00k
            if (render_decorations_in_parent)
6983
3.00k
                window->DrawList = &window->DrawListInst;
6984
9.00k
        }
6985
6986
        // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
6987
6988
        // Work rectangle.
6989
        // Affected by window padding and border size. Used by:
6990
        // - Columns() for right-most edge
6991
        // - TreeNode(), CollapsingHeader() for right-most edge
6992
        // - BeginTabBar() for right-most edge
6993
9.00k
        const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
6994
9.00k
        const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
6995
9.00k
        const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(allow_scrollbar_x ? window->ContentSize.x : 0.0f, window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
6996
9.00k
        const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(allow_scrollbar_y ? window->ContentSize.y : 0.0f, window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
6997
9.00k
        window->WorkRect.Min.x = ImFloor(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize));
6998
9.00k
        window->WorkRect.Min.y = ImFloor(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize));
6999
9.00k
        window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
7000
9.00k
        window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
7001
9.00k
        window->ParentWorkRect = window->WorkRect;
7002
7003
        // [LEGACY] Content Region
7004
        // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
7005
        // Used by:
7006
        // - Mouse wheel scrolling + many other things
7007
9.00k
        window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x + window->DecoOuterSizeX1;
7008
9.00k
        window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->DecoOuterSizeY1;
7009
9.00k
        window->ContentRegionRect.Max.x = window->ContentRegionRect.Min.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
7010
9.00k
        window->ContentRegionRect.Max.y = window->ContentRegionRect.Min.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
7011
7012
        // Setup drawing context
7013
        // (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.)
7014
9.00k
        window->DC.Indent.x = window->DecoOuterSizeX1 + window->WindowPadding.x - window->Scroll.x;
7015
9.00k
        window->DC.GroupOffset.x = 0.0f;
7016
9.00k
        window->DC.ColumnsOffset.x = 0.0f;
7017
7018
        // Record the loss of precision of CursorStartPos which can happen due to really large scrolling amount.
7019
        // This is used by clipper to compensate and fix the most common use case of large scroll area. Easy and cheap, next best thing compared to switching everything to double or ImU64.
7020
9.00k
        double start_pos_highp_x = (double)window->Pos.x + window->WindowPadding.x - (double)window->Scroll.x + window->DecoOuterSizeX1 + window->DC.ColumnsOffset.x;
7021
9.00k
        double start_pos_highp_y = (double)window->Pos.y + window->WindowPadding.y - (double)window->Scroll.y + window->DecoOuterSizeY1;
7022
9.00k
        window->DC.CursorStartPos  = ImVec2((float)start_pos_highp_x, (float)start_pos_highp_y);
7023
9.00k
        window->DC.CursorStartPosLossyness = ImVec2((float)(start_pos_highp_x - window->DC.CursorStartPos.x), (float)(start_pos_highp_y - window->DC.CursorStartPos.y));
7024
9.00k
        window->DC.CursorPos = window->DC.CursorStartPos;
7025
9.00k
        window->DC.CursorPosPrevLine = window->DC.CursorPos;
7026
9.00k
        window->DC.CursorMaxPos = window->DC.CursorStartPos;
7027
9.00k
        window->DC.IdealMaxPos = window->DC.CursorStartPos;
7028
9.00k
        window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
7029
9.00k
        window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
7030
9.00k
        window->DC.IsSameLine = window->DC.IsSetPos = false;
7031
7032
9.00k
        window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7033
9.00k
        window->DC.NavLayersActiveMask = window->DC.NavLayersActiveMaskNext;
7034
9.00k
        window->DC.NavLayersActiveMaskNext = 0x00;
7035
9.00k
        window->DC.NavHideHighlightOneFrame = false;
7036
9.00k
        window->DC.NavHasScroll = (window->ScrollMax.y > 0.0f);
7037
7038
9.00k
        window->DC.MenuBarAppending = false;
7039
9.00k
        window->DC.MenuColumns.Update(style.ItemSpacing.x, window_just_activated_by_user);
7040
9.00k
        window->DC.TreeDepth = 0;
7041
9.00k
        window->DC.TreeJumpToParentOnPopMask = 0x00;
7042
9.00k
        window->DC.ChildWindows.resize(0);
7043
9.00k
        window->DC.StateStorage = &window->StateStorage;
7044
9.00k
        window->DC.CurrentColumns = NULL;
7045
9.00k
        window->DC.LayoutType = ImGuiLayoutType_Vertical;
7046
9.00k
        window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
7047
7048
9.00k
        window->DC.ItemWidth = window->ItemWidthDefault;
7049
9.00k
        window->DC.TextWrapPos = -1.0f; // disabled
7050
9.00k
        window->DC.ItemWidthStack.resize(0);
7051
9.00k
        window->DC.TextWrapPosStack.resize(0);
7052
7053
9.00k
        if (window->AutoFitFramesX > 0)
7054
2
            window->AutoFitFramesX--;
7055
9.00k
        if (window->AutoFitFramesY > 0)
7056
2
            window->AutoFitFramesY--;
7057
7058
        // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
7059
9.00k
        if (want_focus)
7060
2
        {
7061
2
            FocusWindow(window);
7062
2
            NavInitWindow(window, false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls
7063
2
        }
7064
7065
        // Close requested by platform window
7066
9.00k
        if (p_open != NULL && window->Viewport->PlatformRequestClose && window->Viewport != GetMainViewport())
7067
0
        {
7068
0
            if (!window->DockIsActive || window->DockTabIsVisible)
7069
0
            {
7070
0
                window->Viewport->PlatformRequestClose = false;
7071
0
                g.NavWindowingToggleLayer = false; // Assume user mapped PlatformRequestClose on ALT-F4 so we disable ALT for menu toggle. False positive not an issue.
7072
0
                IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' PlatformRequestClose\n", window->Name);
7073
0
                *p_open = false;
7074
0
            }
7075
0
        }
7076
7077
        // Title bar
7078
9.00k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
7079
6.00k
            RenderWindowTitleBarContents(window, ImRect(title_bar_rect.Min.x + window->WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window->WindowBorderSize, title_bar_rect.Max.y), name, p_open);
7080
7081
        // Clear hit test shape every frame
7082
9.00k
        window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
7083
7084
        // Pressing CTRL+C while holding on a window copy its content to the clipboard
7085
        // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope.
7086
        // Maybe we can support CTRL+C on every element?
7087
        /*
7088
        //if (g.NavWindow == window && g.ActiveId == 0)
7089
        if (g.ActiveId == window->MoveId)
7090
            if (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_C))
7091
                LogToClipboard();
7092
        */
7093
7094
9.00k
        if (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)
7095
9.00k
        {
7096
            // Docking: Dragging a dockable window (or any of its child) turns it into a drag and drop source.
7097
            // We need to do this _before_ we overwrite window->DC.LastItemId below because BeginDockableDragDropSource() also overwrites it.
7098
9.00k
            if ((g.MovingWindow == window) && (g.IO.ConfigDockingWithShift == g.IO.KeyShift))
7099
0
                if ((window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoDocking) == 0)
7100
0
                    BeginDockableDragDropSource(window);
7101
7102
            // Docking: Any dockable window can act as a target. For dock node hosts we call BeginDockableDragDropTarget() in DockNodeUpdate() instead.
7103
9.00k
            if (g.DragDropActive && !(flags & ImGuiWindowFlags_NoDocking))
7104
0
                if (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != window)
7105
0
                    if ((window == window->RootWindowDockTree) && !(window->Flags & ImGuiWindowFlags_DockNodeHost))
7106
0
                        BeginDockableDragDropTarget(window);
7107
9.00k
        }
7108
7109
        // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
7110
        // This is useful to allow creating context menus on title bar only, etc.
7111
9.00k
        if (window->DockIsActive)
7112
0
            SetLastItemData(window->MoveId, g.CurrentItemFlags, window->DockTabItemStatusFlags, window->DockTabItemRect);
7113
9.00k
        else
7114
9.00k
            SetLastItemData(window->MoveId, g.CurrentItemFlags, IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0, title_bar_rect);
7115
7116
        // [DEBUG]
7117
9.00k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
7118
9.00k
        if (g.DebugLocateId != 0 && (window->ID == g.DebugLocateId || window->MoveId == g.DebugLocateId))
7119
0
            DebugLocateItemResolveWithLastItem();
7120
9.00k
#endif
7121
7122
        // [Test Engine] Register title bar / tab
7123
#ifdef IMGUI_ENABLE_TEST_ENGINE
7124
        if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
7125
            IMGUI_TEST_ENGINE_ITEM_ADD(g.LastItemData.Rect, g.LastItemData.ID);
7126
#endif
7127
9.00k
    }
7128
0
    else
7129
0
    {
7130
        // Append
7131
0
        SetCurrentViewport(window, window->Viewport);
7132
0
        SetCurrentWindow(window);
7133
0
    }
7134
7135
9.00k
    if (!(flags & ImGuiWindowFlags_DockNodeHost))
7136
9.00k
        PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
7137
7138
    // Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused)
7139
9.00k
    window->WriteAccessed = false;
7140
9.00k
    window->BeginCount++;
7141
9.00k
    g.NextWindowData.ClearFlags();
7142
7143
    // Update visibility
7144
9.00k
    if (first_begin_of_the_frame)
7145
9.00k
    {
7146
        // When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems.
7147
        // This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents.
7148
        // This is analogous to regular windows being hidden from one frame.
7149
        // It is especially important as e.g. nested TabBars would otherwise generate flicker in the form of one empty frame, or focus requests won't be processed.
7150
9.00k
        if (window->DockIsActive && !window->DockTabIsVisible)
7151
0
        {
7152
0
            if (window->LastFrameJustFocused == g.FrameCount)
7153
0
                window->HiddenFramesCannotSkipItems = 1;
7154
0
            else
7155
0
                window->HiddenFramesCanSkipItems = 1;
7156
0
        }
7157
7158
9.00k
        if (flags & ImGuiWindowFlags_ChildWindow)
7159
3.00k
        {
7160
            // Child window can be out of sight and have "negative" clip windows.
7161
            // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
7162
3.00k
            IM_ASSERT((flags& ImGuiWindowFlags_NoTitleBar) != 0 || (window->DockIsActive));
7163
3.00k
            if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) // FIXME: Doesn't make sense for ChildWindow??
7164
3.00k
            {
7165
3.00k
                const bool nav_request = (flags & ImGuiWindowFlags_NavFlattened) && (g.NavAnyRequest && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
7166
3.00k
                if (!g.LogEnabled && !nav_request)
7167
3.00k
                    if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
7168
0
                        window->HiddenFramesCanSkipItems = 1;
7169
3.00k
            }
7170
7171
            // Hide along with parent or if parent is collapsed
7172
3.00k
            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
7173
0
                window->HiddenFramesCanSkipItems = 1;
7174
3.00k
            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0))
7175
1
                window->HiddenFramesCannotSkipItems = 1;
7176
3.00k
        }
7177
7178
        // Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point)
7179
9.00k
        if (style.Alpha <= 0.0f)
7180
0
            window->HiddenFramesCanSkipItems = 1;
7181
7182
        // Update the Hidden flag
7183
9.00k
        bool hidden_regular = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);
7184
9.00k
        window->Hidden = hidden_regular || (window->HiddenFramesForRenderOnly > 0);
7185
7186
        // Disable inputs for requested number of frames
7187
9.00k
        if (window->DisableInputsFrames > 0)
7188
0
        {
7189
0
            window->DisableInputsFrames--;
7190
0
            window->Flags |= ImGuiWindowFlags_NoInputs;
7191
0
        }
7192
7193
        // Update the SkipItems flag, used to early out of all items functions (no layout required)
7194
9.00k
        bool skip_items = false;
7195
9.00k
        if (window->Collapsed || !window->Active || hidden_regular)
7196
2
            if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
7197
0
                skip_items = true;
7198
9.00k
        window->SkipItems = skip_items;
7199
7200
        // Restore NavLayersActiveMaskNext to previous value when not visible, so a CTRL+Tab back can use a safe value.
7201
9.00k
        if (window->SkipItems)
7202
0
            window->DC.NavLayersActiveMaskNext = window->DC.NavLayersActiveMask;
7203
7204
        // Sanity check: there are two spots which can set Appearing = true
7205
        // - when 'window_just_activated_by_user' is set -> HiddenFramesCannotSkipItems is set -> SkipItems always false
7206
        // - in BeginDocked() path when DockNodeIsVisible == DockTabIsVisible == true -> hidden _should_ be all zero // FIXME: Not formally proven, hence the assert.
7207
9.00k
        if (window->SkipItems && !window->Appearing)
7208
9.00k
            IM_ASSERT(window->Appearing == false); // Please report on GitHub if this triggers: https://github.com/ocornut/imgui/issues/4177
7209
9.00k
    }
7210
7211
9.00k
    return !window->SkipItems;
7212
9.00k
}
7213
7214
void ImGui::End()
7215
9.00k
{
7216
9.00k
    ImGuiContext& g = *GImGui;
7217
9.00k
    ImGuiWindow* window = g.CurrentWindow;
7218
7219
    // Error checking: verify that user hasn't called End() too many times!
7220
9.00k
    if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
7221
0
    {
7222
0
        IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
7223
0
        return;
7224
0
    }
7225
9.00k
    IM_ASSERT(g.CurrentWindowStack.Size > 0);
7226
7227
    // Error checking: verify that user doesn't directly call End() on a child window.
7228
9.00k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->DockIsActive)
7229
9.00k
        IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!");
7230
7231
    // Close anything that is open
7232
9.00k
    if (window->DC.CurrentColumns)
7233
0
        EndColumns();
7234
9.00k
    if (!(window->Flags & ImGuiWindowFlags_DockNodeHost))   // Pop inner window clip rectangle
7235
9.00k
        PopClipRect();
7236
9.00k
    PopFocusScope();
7237
7238
    // Stop logging
7239
9.00k
    if (!(window->Flags & ImGuiWindowFlags_ChildWindow))    // FIXME: add more options for scope of logging
7240
6.00k
        LogFinish();
7241
7242
9.00k
    if (window->DC.IsSetPos)
7243
0
        ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
7244
7245
    // Docking: report contents sizes to parent to allow for auto-resize
7246
9.00k
    if (window->DockNode && window->DockTabIsVisible)
7247
0
        if (ImGuiWindow* host_window = window->DockNode->HostWindow)         // FIXME-DOCK
7248
0
            host_window->DC.CursorMaxPos = window->DC.CursorMaxPos + window->WindowPadding - host_window->WindowPadding;
7249
7250
    // Pop from window stack
7251
9.00k
    g.LastItemData = g.CurrentWindowStack.back().ParentLastItemDataBackup;
7252
9.00k
    if (window->Flags & ImGuiWindowFlags_ChildMenu)
7253
0
        g.BeginMenuCount--;
7254
9.00k
    if (window->Flags & ImGuiWindowFlags_Popup)
7255
0
        g.BeginPopupStack.pop_back();
7256
9.00k
    g.CurrentWindowStack.back().StackSizesOnBegin.CompareWithCurrentState();
7257
9.00k
    g.CurrentWindowStack.pop_back();
7258
9.00k
    SetCurrentWindow(g.CurrentWindowStack.Size == 0 ? NULL : g.CurrentWindowStack.back().Window);
7259
9.00k
    if (g.CurrentWindow)
7260
6.00k
        SetCurrentViewport(g.CurrentWindow, g.CurrentWindow->Viewport);
7261
9.00k
}
7262
7263
void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
7264
1.66k
{
7265
1.66k
    ImGuiContext& g = *GImGui;
7266
1.66k
    IM_ASSERT(window == window->RootWindow);
7267
7268
1.66k
    const int cur_order = window->FocusOrder;
7269
1.66k
    IM_ASSERT(g.WindowsFocusOrder[cur_order] == window);
7270
1.66k
    if (g.WindowsFocusOrder.back() == window)
7271
1.66k
        return;
7272
7273
0
    const int new_order = g.WindowsFocusOrder.Size - 1;
7274
0
    for (int n = cur_order; n < new_order; n++)
7275
0
    {
7276
0
        g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1];
7277
0
        g.WindowsFocusOrder[n]->FocusOrder--;
7278
0
        IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n);
7279
0
    }
7280
0
    g.WindowsFocusOrder[new_order] = window;
7281
0
    window->FocusOrder = (short)new_order;
7282
0
}
7283
7284
void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
7285
1.66k
{
7286
1.66k
    ImGuiContext& g = *GImGui;
7287
1.66k
    ImGuiWindow* current_front_window = g.Windows.back();
7288
1.66k
    if (current_front_window == window || current_front_window->RootWindowDockTree == window) // Cheap early out (could be better)
7289
1.66k
        return;
7290
0
    for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
7291
0
        if (g.Windows[i] == window)
7292
0
        {
7293
0
            memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
7294
0
            g.Windows[g.Windows.Size - 1] = window;
7295
0
            break;
7296
0
        }
7297
0
}
7298
7299
void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
7300
0
{
7301
0
    ImGuiContext& g = *GImGui;
7302
0
    if (g.Windows[0] == window)
7303
0
        return;
7304
0
    for (int i = 0; i < g.Windows.Size; i++)
7305
0
        if (g.Windows[i] == window)
7306
0
        {
7307
0
            memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
7308
0
            g.Windows[0] = window;
7309
0
            break;
7310
0
        }
7311
0
}
7312
7313
void ImGui::BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* behind_window)
7314
0
{
7315
0
    IM_ASSERT(window != NULL && behind_window != NULL);
7316
0
    ImGuiContext& g = *GImGui;
7317
0
    window = window->RootWindow;
7318
0
    behind_window = behind_window->RootWindow;
7319
0
    int pos_wnd = FindWindowDisplayIndex(window);
7320
0
    int pos_beh = FindWindowDisplayIndex(behind_window);
7321
0
    if (pos_wnd < pos_beh)
7322
0
    {
7323
0
        size_t copy_bytes = (pos_beh - pos_wnd - 1) * sizeof(ImGuiWindow*);
7324
0
        memmove(&g.Windows.Data[pos_wnd], &g.Windows.Data[pos_wnd + 1], copy_bytes);
7325
0
        g.Windows[pos_beh - 1] = window;
7326
0
    }
7327
0
    else
7328
0
    {
7329
0
        size_t copy_bytes = (pos_wnd - pos_beh) * sizeof(ImGuiWindow*);
7330
0
        memmove(&g.Windows.Data[pos_beh + 1], &g.Windows.Data[pos_beh], copy_bytes);
7331
0
        g.Windows[pos_beh] = window;
7332
0
    }
7333
0
}
7334
7335
int ImGui::FindWindowDisplayIndex(ImGuiWindow* window)
7336
0
{
7337
0
    ImGuiContext& g = *GImGui;
7338
0
    return g.Windows.index_from_ptr(g.Windows.find(window));
7339
0
}
7340
7341
// Moving window to front of display and set focus (which happens to be back of our sorted list)
7342
void ImGui::FocusWindow(ImGuiWindow* window)
7343
2.71k
{
7344
2.71k
    ImGuiContext& g = *GImGui;
7345
7346
2.71k
    if (g.NavWindow != window)
7347
903
    {
7348
903
        SetNavWindow(window);
7349
903
        if (window && g.NavDisableMouseHover)
7350
0
            g.NavMousePosDirty = true;
7351
903
        g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
7352
903
        g.NavLayer = ImGuiNavLayer_Main;
7353
903
        g.NavFocusScopeId = window ? window->NavRootFocusScopeId : 0;
7354
903
        g.NavIdIsAlive = false;
7355
7356
        // Close popups if any
7357
903
        ClosePopupsOverWindow(window, false);
7358
903
    }
7359
7360
    // Move the root window to the top of the pile
7361
2.71k
    IM_ASSERT(window == NULL || window->RootWindowDockTree != NULL);
7362
2.71k
    ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL;
7363
2.71k
    ImGuiWindow* display_front_window = window ? window->RootWindowDockTree : NULL;
7364
2.71k
    ImGuiDockNode* dock_node = window ? window->DockNode : NULL;
7365
2.71k
    bool active_id_window_is_dock_node_host = (g.ActiveIdWindow && dock_node && dock_node->HostWindow == g.ActiveIdWindow);
7366
7367
    // Steal active widgets. Some of the cases it triggers includes:
7368
    // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run.
7369
    // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId)
7370
    // - Using dock host items (tab, collapse button) can trigger this before we redirect the ActiveIdWindow toward the child window.
7371
2.71k
    if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
7372
0
        if (!g.ActiveIdNoClearOnFocusLoss && !active_id_window_is_dock_node_host)
7373
0
            ClearActiveID();
7374
7375
    // Passing NULL allow to disable keyboard focus
7376
2.71k
    if (!window)
7377
1.04k
        return;
7378
1.66k
    window->LastFrameJustFocused = g.FrameCount;
7379
7380
    // Select in dock node
7381
1.66k
    if (dock_node && dock_node->TabBar)
7382
0
        dock_node->TabBar->SelectedTabId = dock_node->TabBar->NextSelectedTabId = window->TabId;
7383
7384
    // Bring to front
7385
1.66k
    BringWindowToFocusFront(focus_front_window);
7386
1.66k
    if (((window->Flags | focus_front_window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
7387
1.66k
        BringWindowToDisplayFront(display_front_window);
7388
1.66k
}
7389
7390
void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window)
7391
0
{
7392
0
    ImGuiContext& g = *GImGui;
7393
0
    int start_idx = g.WindowsFocusOrder.Size - 1;
7394
0
    if (under_this_window != NULL)
7395
0
    {
7396
        // Aim at root window behind us, if we are in a child window that's our own root (see #4640)
7397
0
        int offset = -1;
7398
0
        while (under_this_window->Flags & ImGuiWindowFlags_ChildWindow)
7399
0
        {
7400
0
            under_this_window = under_this_window->ParentWindow;
7401
0
            offset = 0;
7402
0
        }
7403
0
        start_idx = FindWindowFocusIndex(under_this_window) + offset;
7404
0
    }
7405
0
    for (int i = start_idx; i >= 0; i--)
7406
0
    {
7407
        // We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user.
7408
0
        ImGuiWindow* window = g.WindowsFocusOrder[i];
7409
0
        IM_ASSERT(window == window->RootWindow);
7410
0
        if (window != ignore_window && window->WasActive)
7411
0
            if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
7412
0
            {
7413
                // FIXME-DOCK: This is failing (lagging by one frame) for docked windows.
7414
                // If A and B are docked into window and B disappear, at the NewFrame() call site window->NavLastChildNavWindow will still point to B.
7415
                // We might leverage the tab order implicitly stored in window->DockNodeAsHost->TabBar (essentially the 'most_recently_selected_tab' code in tab bar will do that but on next update)
7416
                // to tell which is the "previous" window. Or we may leverage 'LastFrameFocused/LastFrameJustFocused' and have this function handle child window itself?
7417
0
                ImGuiWindow* focus_window = NavRestoreLastChildNavWindow(window);
7418
0
                FocusWindow(focus_window);
7419
0
                return;
7420
0
            }
7421
0
    }
7422
0
    FocusWindow(NULL);
7423
0
}
7424
7425
// Important: this alone doesn't alter current ImDrawList state. This is called by PushFont/PopFont only.
7426
void ImGui::SetCurrentFont(ImFont* font)
7427
3.00k
{
7428
3.00k
    ImGuiContext& g = *GImGui;
7429
3.00k
    IM_ASSERT(font && font->IsLoaded());    // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
7430
3.00k
    IM_ASSERT(font->Scale > 0.0f);
7431
3.00k
    g.Font = font;
7432
3.00k
    g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale);
7433
3.00k
    g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
7434
7435
3.00k
    ImFontAtlas* atlas = g.Font->ContainerAtlas;
7436
3.00k
    g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
7437
3.00k
    g.DrawListSharedData.TexUvLines = atlas->TexUvLines;
7438
3.00k
    g.DrawListSharedData.Font = g.Font;
7439
3.00k
    g.DrawListSharedData.FontSize = g.FontSize;
7440
3.00k
}
7441
7442
void ImGui::PushFont(ImFont* font)
7443
0
{
7444
0
    ImGuiContext& g = *GImGui;
7445
0
    if (!font)
7446
0
        font = GetDefaultFont();
7447
0
    SetCurrentFont(font);
7448
0
    g.FontStack.push_back(font);
7449
0
    g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);
7450
0
}
7451
7452
void  ImGui::PopFont()
7453
0
{
7454
0
    ImGuiContext& g = *GImGui;
7455
0
    g.CurrentWindow->DrawList->PopTextureID();
7456
0
    g.FontStack.pop_back();
7457
0
    SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
7458
0
}
7459
7460
void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
7461
3.00k
{
7462
3.00k
    ImGuiContext& g = *GImGui;
7463
3.00k
    ImGuiItemFlags item_flags = g.CurrentItemFlags;
7464
3.00k
    IM_ASSERT(item_flags == g.ItemFlagsStack.back());
7465
3.00k
    if (enabled)
7466
0
        item_flags |= option;
7467
3.00k
    else
7468
3.00k
        item_flags &= ~option;
7469
3.00k
    g.CurrentItemFlags = item_flags;
7470
3.00k
    g.ItemFlagsStack.push_back(item_flags);
7471
3.00k
}
7472
7473
void ImGui::PopItemFlag()
7474
3.00k
{
7475
3.00k
    ImGuiContext& g = *GImGui;
7476
3.00k
    IM_ASSERT(g.ItemFlagsStack.Size > 1); // Too many calls to PopItemFlag() - we always leave a 0 at the bottom of the stack.
7477
3.00k
    g.ItemFlagsStack.pop_back();
7478
3.00k
    g.CurrentItemFlags = g.ItemFlagsStack.back();
7479
3.00k
}
7480
7481
// BeginDisabled()/EndDisabled()
7482
// - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled)
7483
// - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently.
7484
// - Feedback welcome at https://github.com/ocornut/imgui/issues/211
7485
// - BeginDisabled(false) essentially does nothing useful but is provided to facilitate use of boolean expressions. If you can avoid calling BeginDisabled(False)/EndDisabled() best to avoid it.
7486
// - Optimized shortcuts instead of PushStyleVar() + PushItemFlag()
7487
void ImGui::BeginDisabled(bool disabled)
7488
0
{
7489
0
    ImGuiContext& g = *GImGui;
7490
0
    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
7491
0
    if (!was_disabled && disabled)
7492
0
    {
7493
0
        g.DisabledAlphaBackup = g.Style.Alpha;
7494
0
        g.Style.Alpha *= g.Style.DisabledAlpha; // PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * g.Style.DisabledAlpha);
7495
0
    }
7496
0
    if (was_disabled || disabled)
7497
0
        g.CurrentItemFlags |= ImGuiItemFlags_Disabled;
7498
0
    g.ItemFlagsStack.push_back(g.CurrentItemFlags);
7499
0
    g.DisabledStackSize++;
7500
0
}
7501
7502
void ImGui::EndDisabled()
7503
0
{
7504
0
    ImGuiContext& g = *GImGui;
7505
0
    IM_ASSERT(g.DisabledStackSize > 0);
7506
0
    g.DisabledStackSize--;
7507
0
    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
7508
    //PopItemFlag();
7509
0
    g.ItemFlagsStack.pop_back();
7510
0
    g.CurrentItemFlags = g.ItemFlagsStack.back();
7511
0
    if (was_disabled && (g.CurrentItemFlags & ImGuiItemFlags_Disabled) == 0)
7512
0
        g.Style.Alpha = g.DisabledAlphaBackup; //PopStyleVar();
7513
0
}
7514
7515
// FIXME: Look into renaming this once we have settled the new Focus/Activation/TabStop system.
7516
void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus)
7517
3.00k
{
7518
3.00k
    PushItemFlag(ImGuiItemFlags_NoTabStop, !allow_keyboard_focus);
7519
3.00k
}
7520
7521
void ImGui::PopAllowKeyboardFocus()
7522
3.00k
{
7523
3.00k
    PopItemFlag();
7524
3.00k
}
7525
7526
void ImGui::PushButtonRepeat(bool repeat)
7527
0
{
7528
0
    PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat);
7529
0
}
7530
7531
void ImGui::PopButtonRepeat()
7532
0
{
7533
0
    PopItemFlag();
7534
0
}
7535
7536
void ImGui::PushTextWrapPos(float wrap_pos_x)
7537
0
{
7538
0
    ImGuiWindow* window = GetCurrentWindow();
7539
0
    window->DC.TextWrapPosStack.push_back(window->DC.TextWrapPos);
7540
0
    window->DC.TextWrapPos = wrap_pos_x;
7541
0
}
7542
7543
void ImGui::PopTextWrapPos()
7544
0
{
7545
0
    ImGuiWindow* window = GetCurrentWindow();
7546
0
    window->DC.TextWrapPos = window->DC.TextWrapPosStack.back();
7547
0
    window->DC.TextWrapPosStack.pop_back();
7548
0
}
7549
7550
static ImGuiWindow* GetCombinedRootWindow(ImGuiWindow* window, bool popup_hierarchy, bool dock_hierarchy)
7551
0
{
7552
0
    ImGuiWindow* last_window = NULL;
7553
0
    while (last_window != window)
7554
0
    {
7555
0
        last_window = window;
7556
0
        window = window->RootWindow;
7557
0
        if (popup_hierarchy)
7558
0
            window = window->RootWindowPopupTree;
7559
0
    if (dock_hierarchy)
7560
0
      window = window->RootWindowDockTree;
7561
0
  }
7562
0
    return window;
7563
0
}
7564
7565
bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy, bool dock_hierarchy)
7566
0
{
7567
0
    ImGuiWindow* window_root = GetCombinedRootWindow(window, popup_hierarchy, dock_hierarchy);
7568
0
    if (window_root == potential_parent)
7569
0
        return true;
7570
0
    while (window != NULL)
7571
0
    {
7572
0
        if (window == potential_parent)
7573
0
            return true;
7574
0
        if (window == window_root) // end of chain
7575
0
            return false;
7576
0
        window = window->ParentWindow;
7577
0
    }
7578
0
    return false;
7579
0
}
7580
7581
bool ImGui::IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
7582
0
{
7583
0
    if (window->RootWindow == potential_parent)
7584
0
        return true;
7585
0
    while (window != NULL)
7586
0
    {
7587
0
        if (window == potential_parent)
7588
0
            return true;
7589
0
        window = window->ParentWindowInBeginStack;
7590
0
    }
7591
0
    return false;
7592
0
}
7593
7594
bool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below)
7595
0
{
7596
0
    ImGuiContext& g = *GImGui;
7597
7598
    // It would be saner to ensure that display layer is always reflected in the g.Windows[] order, which would likely requires altering all manipulations of that array
7599
0
    const int display_layer_delta = GetWindowDisplayLayer(potential_above) - GetWindowDisplayLayer(potential_below);
7600
0
    if (display_layer_delta != 0)
7601
0
        return display_layer_delta > 0;
7602
7603
0
    for (int i = g.Windows.Size - 1; i >= 0; i--)
7604
0
    {
7605
0
        ImGuiWindow* candidate_window = g.Windows[i];
7606
0
        if (candidate_window == potential_above)
7607
0
            return true;
7608
0
        if (candidate_window == potential_below)
7609
0
            return false;
7610
0
    }
7611
0
    return false;
7612
0
}
7613
7614
bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
7615
5.08k
{
7616
5.08k
    IM_ASSERT((flags & (ImGuiHoveredFlags_AllowWhenOverlapped | ImGuiHoveredFlags_AllowWhenDisabled)) == 0);   // Flags not supported by this function
7617
5.08k
    ImGuiContext& g = *GImGui;
7618
5.08k
    ImGuiWindow* ref_window = g.HoveredWindow;
7619
5.08k
    ImGuiWindow* cur_window = g.CurrentWindow;
7620
5.08k
    if (ref_window == NULL)
7621
5.08k
        return false;
7622
7623
0
    if ((flags & ImGuiHoveredFlags_AnyWindow) == 0)
7624
0
    {
7625
0
        IM_ASSERT(cur_window); // Not inside a Begin()/End()
7626
0
        const bool popup_hierarchy = (flags & ImGuiHoveredFlags_NoPopupHierarchy) == 0;
7627
0
        const bool dock_hierarchy = (flags & ImGuiHoveredFlags_DockHierarchy) != 0;
7628
0
        if (flags & ImGuiHoveredFlags_RootWindow)
7629
0
            cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
7630
7631
0
        bool result;
7632
0
        if (flags & ImGuiHoveredFlags_ChildWindows)
7633
0
            result = IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
7634
0
        else
7635
0
            result = (ref_window == cur_window);
7636
0
        if (!result)
7637
0
            return false;
7638
0
    }
7639
7640
0
    if (!IsWindowContentHoverable(ref_window, flags))
7641
0
        return false;
7642
0
    if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
7643
0
        if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != ref_window->MoveId)
7644
0
            return false;
7645
0
    return true;
7646
0
}
7647
7648
bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
7649
5.79k
{
7650
5.79k
    ImGuiContext& g = *GImGui;
7651
5.79k
    ImGuiWindow* ref_window = g.NavWindow;
7652
5.79k
    ImGuiWindow* cur_window = g.CurrentWindow;
7653
7654
5.79k
    if (ref_window == NULL)
7655
1.70k
        return false;
7656
4.08k
    if (flags & ImGuiFocusedFlags_AnyWindow)
7657
0
        return true;
7658
7659
4.08k
    IM_ASSERT(cur_window); // Not inside a Begin()/End()
7660
4.08k
    const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0;
7661
4.08k
    const bool dock_hierarchy = (flags & ImGuiFocusedFlags_DockHierarchy) != 0;
7662
4.08k
    if (flags & ImGuiHoveredFlags_RootWindow)
7663
0
        cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
7664
7665
4.08k
    if (flags & ImGuiHoveredFlags_ChildWindows)
7666
0
        return IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
7667
4.08k
    else
7668
4.08k
        return (ref_window == cur_window);
7669
4.08k
}
7670
7671
ImGuiID ImGui::GetWindowDockID()
7672
0
{
7673
0
    ImGuiContext& g = *GImGui;
7674
0
    return g.CurrentWindow->DockId;
7675
0
}
7676
7677
bool ImGui::IsWindowDocked()
7678
0
{
7679
0
    ImGuiContext& g = *GImGui;
7680
0
    return g.CurrentWindow->DockIsActive;
7681
0
}
7682
7683
// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
7684
// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically.
7685
// If you want a window to never be focused, you may use the e.g. NoInputs flag.
7686
bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
7687
0
{
7688
0
    return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
7689
0
}
7690
7691
float ImGui::GetWindowWidth()
7692
1.66k
{
7693
1.66k
    ImGuiWindow* window = GImGui->CurrentWindow;
7694
1.66k
    return window->Size.x;
7695
1.66k
}
7696
7697
float ImGui::GetWindowHeight()
7698
1.69k
{
7699
1.69k
    ImGuiWindow* window = GImGui->CurrentWindow;
7700
1.69k
    return window->Size.y;
7701
1.69k
}
7702
7703
ImVec2 ImGui::GetWindowPos()
7704
0
{
7705
0
    ImGuiContext& g = *GImGui;
7706
0
    ImGuiWindow* window = g.CurrentWindow;
7707
0
    return window->Pos;
7708
0
}
7709
7710
void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
7711
0
{
7712
    // Test condition (NB: bit 0 is always true) and clear flags for next time
7713
0
    if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
7714
0
        return;
7715
7716
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
7717
0
    window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
7718
0
    window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
7719
7720
    // Set
7721
0
    const ImVec2 old_pos = window->Pos;
7722
0
    window->Pos = ImFloor(pos);
7723
0
    ImVec2 offset = window->Pos - old_pos;
7724
0
    if (offset.x == 0.0f && offset.y == 0.0f)
7725
0
        return;
7726
0
    MarkIniSettingsDirty(window);
7727
    // FIXME: share code with TranslateWindow(), need to confirm whether the 3 rect modified by TranslateWindow() are desirable here.
7728
0
    window->DC.CursorPos += offset;         // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor
7729
0
    window->DC.CursorMaxPos += offset;      // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
7730
0
    window->DC.IdealMaxPos += offset;
7731
0
    window->DC.CursorStartPos += offset;
7732
0
}
7733
7734
void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
7735
0
{
7736
0
    ImGuiWindow* window = GetCurrentWindowRead();
7737
0
    SetWindowPos(window, pos, cond);
7738
0
}
7739
7740
void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
7741
0
{
7742
0
    if (ImGuiWindow* window = FindWindowByName(name))
7743
0
        SetWindowPos(window, pos, cond);
7744
0
}
7745
7746
ImVec2 ImGui::GetWindowSize()
7747
0
{
7748
0
    ImGuiWindow* window = GetCurrentWindowRead();
7749
0
    return window->Size;
7750
0
}
7751
7752
void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
7753
6.00k
{
7754
    // Test condition (NB: bit 0 is always true) and clear flags for next time
7755
6.00k
    if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
7756
3.00k
        return;
7757
7758
3.00k
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
7759
3.00k
    window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
7760
7761
    // Set
7762
3.00k
    ImVec2 old_size = window->SizeFull;
7763
3.00k
    window->AutoFitFramesX = (size.x <= 0.0f) ? 2 : 0;
7764
3.00k
    window->AutoFitFramesY = (size.y <= 0.0f) ? 2 : 0;
7765
3.00k
    if (size.x <= 0.0f)
7766
0
        window->AutoFitOnlyGrows = false;
7767
3.00k
    else
7768
3.00k
        window->SizeFull.x = IM_FLOOR(size.x);
7769
3.00k
    if (size.y <= 0.0f)
7770
0
        window->AutoFitOnlyGrows = false;
7771
3.00k
    else
7772
3.00k
        window->SizeFull.y = IM_FLOOR(size.y);
7773
3.00k
    if (old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y)
7774
562
        MarkIniSettingsDirty(window);
7775
3.00k
}
7776
7777
void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
7778
0
{
7779
0
    SetWindowSize(GImGui->CurrentWindow, size, cond);
7780
0
}
7781
7782
void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
7783
0
{
7784
0
    if (ImGuiWindow* window = FindWindowByName(name))
7785
0
        SetWindowSize(window, size, cond);
7786
0
}
7787
7788
void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
7789
0
{
7790
    // Test condition (NB: bit 0 is always true) and clear flags for next time
7791
0
    if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
7792
0
        return;
7793
0
    window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
7794
7795
    // Set
7796
0
    window->Collapsed = collapsed;
7797
0
}
7798
7799
void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
7800
0
{
7801
0
    IM_ASSERT(window->HitTestHoleSize.x == 0);     // We don't support multiple holes/hit test filters
7802
0
    window->HitTestHoleSize = ImVec2ih(size);
7803
0
    window->HitTestHoleOffset = ImVec2ih(pos - window->Pos);
7804
0
}
7805
7806
void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
7807
0
{
7808
0
    SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
7809
0
}
7810
7811
bool ImGui::IsWindowCollapsed()
7812
0
{
7813
0
    ImGuiWindow* window = GetCurrentWindowRead();
7814
0
    return window->Collapsed;
7815
0
}
7816
7817
bool ImGui::IsWindowAppearing()
7818
0
{
7819
0
    ImGuiWindow* window = GetCurrentWindowRead();
7820
0
    return window->Appearing;
7821
0
}
7822
7823
void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
7824
0
{
7825
0
    if (ImGuiWindow* window = FindWindowByName(name))
7826
0
        SetWindowCollapsed(window, collapsed, cond);
7827
0
}
7828
7829
void ImGui::SetWindowFocus()
7830
1.66k
{
7831
1.66k
    FocusWindow(GImGui->CurrentWindow);
7832
1.66k
}
7833
7834
void ImGui::SetWindowFocus(const char* name)
7835
0
{
7836
0
    if (name)
7837
0
    {
7838
0
        if (ImGuiWindow* window = FindWindowByName(name))
7839
0
            FocusWindow(window);
7840
0
    }
7841
0
    else
7842
0
    {
7843
0
        FocusWindow(NULL);
7844
0
    }
7845
0
}
7846
7847
void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
7848
0
{
7849
0
    ImGuiContext& g = *GImGui;
7850
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
7851
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos;
7852
0
    g.NextWindowData.PosVal = pos;
7853
0
    g.NextWindowData.PosPivotVal = pivot;
7854
0
    g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
7855
0
    g.NextWindowData.PosUndock = true;
7856
0
}
7857
7858
void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
7859
6.00k
{
7860
6.00k
    ImGuiContext& g = *GImGui;
7861
6.00k
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
7862
6.00k
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize;
7863
6.00k
    g.NextWindowData.SizeVal = size;
7864
6.00k
    g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
7865
6.00k
}
7866
7867
void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
7868
0
{
7869
0
    ImGuiContext& g = *GImGui;
7870
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
7871
0
    g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
7872
0
    g.NextWindowData.SizeCallback = custom_callback;
7873
0
    g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
7874
0
}
7875
7876
// Content size = inner scrollable rectangle, padded with WindowPadding.
7877
// SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
7878
void ImGui::SetNextWindowContentSize(const ImVec2& size)
7879
0
{
7880
0
    ImGuiContext& g = *GImGui;
7881
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize;
7882
0
    g.NextWindowData.ContentSizeVal = ImFloor(size);
7883
0
}
7884
7885
void ImGui::SetNextWindowScroll(const ImVec2& scroll)
7886
0
{
7887
0
    ImGuiContext& g = *GImGui;
7888
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasScroll;
7889
0
    g.NextWindowData.ScrollVal = scroll;
7890
0
}
7891
7892
void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
7893
0
{
7894
0
    ImGuiContext& g = *GImGui;
7895
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
7896
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed;
7897
0
    g.NextWindowData.CollapsedVal = collapsed;
7898
0
    g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
7899
0
}
7900
7901
void ImGui::SetNextWindowFocus()
7902
0
{
7903
0
    ImGuiContext& g = *GImGui;
7904
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus;
7905
0
}
7906
7907
void ImGui::SetNextWindowBgAlpha(float alpha)
7908
0
{
7909
0
    ImGuiContext& g = *GImGui;
7910
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha;
7911
0
    g.NextWindowData.BgAlphaVal = alpha;
7912
0
}
7913
7914
void ImGui::SetNextWindowViewport(ImGuiID id)
7915
0
{
7916
0
    ImGuiContext& g = *GImGui;
7917
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasViewport;
7918
0
    g.NextWindowData.ViewportId = id;
7919
0
}
7920
7921
void ImGui::SetNextWindowDockID(ImGuiID id, ImGuiCond cond)
7922
0
{
7923
0
    ImGuiContext& g = *GImGui;
7924
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasDock;
7925
0
    g.NextWindowData.DockCond = cond ? cond : ImGuiCond_Always;
7926
0
    g.NextWindowData.DockId = id;
7927
0
}
7928
7929
void ImGui::SetNextWindowClass(const ImGuiWindowClass* window_class)
7930
0
{
7931
0
    ImGuiContext& g = *GImGui;
7932
0
    IM_ASSERT((window_class->ViewportFlagsOverrideSet & window_class->ViewportFlagsOverrideClear) == 0); // Cannot set both set and clear for the same bit
7933
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasWindowClass;
7934
0
    g.NextWindowData.WindowClass = *window_class;
7935
0
}
7936
7937
ImDrawList* ImGui::GetWindowDrawList()
7938
3.00k
{
7939
3.00k
    ImGuiWindow* window = GetCurrentWindow();
7940
3.00k
    return window->DrawList;
7941
3.00k
}
7942
7943
float ImGui::GetWindowDpiScale()
7944
0
{
7945
0
    ImGuiContext& g = *GImGui;
7946
0
    return g.CurrentDpiScale;
7947
0
}
7948
7949
ImGuiViewport* ImGui::GetWindowViewport()
7950
0
{
7951
0
    ImGuiContext& g = *GImGui;
7952
0
    IM_ASSERT(g.CurrentViewport != NULL && g.CurrentViewport == g.CurrentWindow->Viewport);
7953
0
    return g.CurrentViewport;
7954
0
}
7955
7956
ImFont* ImGui::GetFont()
7957
9.55M
{
7958
9.55M
    return GImGui->Font;
7959
9.55M
}
7960
7961
float ImGui::GetFontSize()
7962
9.55M
{
7963
9.55M
    return GImGui->FontSize;
7964
9.55M
}
7965
7966
ImVec2 ImGui::GetFontTexUvWhitePixel()
7967
0
{
7968
0
    return GImGui->DrawListSharedData.TexUvWhitePixel;
7969
0
}
7970
7971
void ImGui::SetWindowFontScale(float scale)
7972
0
{
7973
0
    IM_ASSERT(scale > 0.0f);
7974
0
    ImGuiContext& g = *GImGui;
7975
0
    ImGuiWindow* window = GetCurrentWindow();
7976
0
    window->FontWindowScale = scale;
7977
0
    g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
7978
0
}
7979
7980
void ImGui::ActivateItem(ImGuiID id)
7981
0
{
7982
0
    ImGuiContext& g = *GImGui;
7983
0
    g.NavNextActivateId = id;
7984
0
    g.NavNextActivateFlags = ImGuiActivateFlags_None;
7985
0
}
7986
7987
void ImGui::PushFocusScope(ImGuiID id)
7988
9.00k
{
7989
9.00k
    ImGuiContext& g = *GImGui;
7990
9.00k
    g.FocusScopeStack.push_back(id);
7991
9.00k
    g.CurrentFocusScopeId = id;
7992
9.00k
}
7993
7994
void ImGui::PopFocusScope()
7995
9.00k
{
7996
9.00k
    ImGuiContext& g = *GImGui;
7997
9.00k
    IM_ASSERT(g.FocusScopeStack.Size > 0); // Too many PopFocusScope() ?
7998
9.00k
    g.FocusScopeStack.pop_back();
7999
9.00k
    g.CurrentFocusScopeId = g.FocusScopeStack.Size ? g.FocusScopeStack.back() : 0;
8000
9.00k
}
8001
8002
// Note: this will likely be called ActivateItem() once we rework our Focus/Activation system!
8003
void ImGui::SetKeyboardFocusHere(int offset)
8004
0
{
8005
0
    ImGuiContext& g = *GImGui;
8006
0
    ImGuiWindow* window = g.CurrentWindow;
8007
0
    IM_ASSERT(offset >= -1);    // -1 is allowed but not below
8008
0
    IMGUI_DEBUG_LOG_ACTIVEID("SetKeyboardFocusHere(%d) in window \"%s\"\n", offset, window->Name);
8009
8010
    // It makes sense in the vast majority of cases to never interrupt a drag and drop.
8011
    // When we refactor this function into ActivateItem() we may want to make this an option.
8012
    // MovingWindow is protected from most user inputs using SetActiveIdUsingNavAndKeys(), but
8013
    // is also automatically dropped in the event g.ActiveId is stolen.
8014
0
    if (g.DragDropActive || g.MovingWindow != NULL)
8015
0
    {
8016
0
        IMGUI_DEBUG_LOG_ACTIVEID("SetKeyboardFocusHere() ignored while DragDropActive!\n");
8017
0
        return;
8018
0
    }
8019
8020
0
    SetNavWindow(window);
8021
8022
0
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8023
0
    NavMoveRequestSubmit(ImGuiDir_None, offset < 0 ? ImGuiDir_Up : ImGuiDir_Down, ImGuiNavMoveFlags_Tabbing | ImGuiNavMoveFlags_FocusApi, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
8024
0
    if (offset == -1)
8025
0
    {
8026
0
        NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
8027
0
    }
8028
0
    else
8029
0
    {
8030
0
        g.NavTabbingDir = 1;
8031
0
        g.NavTabbingCounter = offset + 1;
8032
0
    }
8033
0
}
8034
8035
void ImGui::SetItemDefaultFocus()
8036
0
{
8037
0
    ImGuiContext& g = *GImGui;
8038
0
    ImGuiWindow* window = g.CurrentWindow;
8039
0
    if (!window->Appearing)
8040
0
        return;
8041
0
    if (g.NavWindow != window->RootWindowForNav || (!g.NavInitRequest && g.NavInitResultId == 0) || g.NavLayer != window->DC.NavLayerCurrent)
8042
0
        return;
8043
8044
0
    g.NavInitRequest = false;
8045
0
    g.NavInitResultId = g.LastItemData.ID;
8046
0
    g.NavInitResultRectRel = WindowRectAbsToRel(window, g.LastItemData.Rect);
8047
0
    NavUpdateAnyRequestFlag();
8048
8049
    // Scroll could be done in NavInitRequestApplyResult() via an opt-in flag (we however don't want regular init requests to scroll)
8050
0
    if (!IsItemVisible())
8051
0
        ScrollToRectEx(window, g.LastItemData.Rect, ImGuiScrollFlags_None);
8052
0
}
8053
8054
void ImGui::SetStateStorage(ImGuiStorage* tree)
8055
0
{
8056
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8057
0
    window->DC.StateStorage = tree ? tree : &window->StateStorage;
8058
0
}
8059
8060
ImGuiStorage* ImGui::GetStateStorage()
8061
0
{
8062
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8063
0
    return window->DC.StateStorage;
8064
0
}
8065
8066
void ImGui::PushID(const char* str_id)
8067
3.00k
{
8068
3.00k
    ImGuiContext& g = *GImGui;
8069
3.00k
    ImGuiWindow* window = g.CurrentWindow;
8070
3.00k
    ImGuiID id = window->GetID(str_id);
8071
3.00k
    window->IDStack.push_back(id);
8072
3.00k
}
8073
8074
void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
8075
0
{
8076
0
    ImGuiContext& g = *GImGui;
8077
0
    ImGuiWindow* window = g.CurrentWindow;
8078
0
    ImGuiID id = window->GetID(str_id_begin, str_id_end);
8079
0
    window->IDStack.push_back(id);
8080
0
}
8081
8082
void ImGui::PushID(const void* ptr_id)
8083
0
{
8084
0
    ImGuiContext& g = *GImGui;
8085
0
    ImGuiWindow* window = g.CurrentWindow;
8086
0
    ImGuiID id = window->GetID(ptr_id);
8087
0
    window->IDStack.push_back(id);
8088
0
}
8089
8090
void ImGui::PushID(int int_id)
8091
0
{
8092
0
    ImGuiContext& g = *GImGui;
8093
0
    ImGuiWindow* window = g.CurrentWindow;
8094
0
    ImGuiID id = window->GetID(int_id);
8095
0
    window->IDStack.push_back(id);
8096
0
}
8097
8098
// Push a given id value ignoring the ID stack as a seed.
8099
void ImGui::PushOverrideID(ImGuiID id)
8100
0
{
8101
0
    ImGuiContext& g = *GImGui;
8102
0
    ImGuiWindow* window = g.CurrentWindow;
8103
0
    if (g.DebugHookIdInfo == id)
8104
0
        DebugHookIdInfo(id, ImGuiDataType_ID, NULL, NULL);
8105
0
    window->IDStack.push_back(id);
8106
0
}
8107
8108
// Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call
8109
// (note that when using this pattern, TestEngine's "Stack Tool" will tend to not display the intermediate stack level.
8110
//  for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more)
8111
ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed)
8112
0
{
8113
0
    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
8114
0
    ImGuiContext& g = *GImGui;
8115
0
    if (g.DebugHookIdInfo == id)
8116
0
        DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
8117
0
    return id;
8118
0
}
8119
8120
ImGuiID ImGui::GetIDWithSeed(int n, ImGuiID seed)
8121
0
{
8122
0
    ImGuiID id = ImHashData(&n, sizeof(n), seed);
8123
0
    ImGuiContext& g = *GImGui;
8124
0
    if (g.DebugHookIdInfo == id)
8125
0
        DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
8126
0
    return id;
8127
0
}
8128
8129
void ImGui::PopID()
8130
3.00k
{
8131
3.00k
    ImGuiWindow* window = GImGui->CurrentWindow;
8132
3.00k
    IM_ASSERT(window->IDStack.Size > 1); // Too many PopID(), or could be popping in a wrong/different window?
8133
3.00k
    window->IDStack.pop_back();
8134
3.00k
}
8135
8136
ImGuiID ImGui::GetID(const char* str_id)
8137
0
{
8138
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8139
0
    return window->GetID(str_id);
8140
0
}
8141
8142
ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
8143
0
{
8144
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8145
0
    return window->GetID(str_id_begin, str_id_end);
8146
0
}
8147
8148
ImGuiID ImGui::GetID(const void* ptr_id)
8149
0
{
8150
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8151
0
    return window->GetID(ptr_id);
8152
0
}
8153
8154
bool ImGui::IsRectVisible(const ImVec2& size)
8155
0
{
8156
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8157
0
    return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
8158
0
}
8159
8160
bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
8161
0
{
8162
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8163
0
    return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
8164
0
}
8165
8166
8167
//-----------------------------------------------------------------------------
8168
// [SECTION] INPUTS
8169
//-----------------------------------------------------------------------------
8170
// - GetKeyData() [Internal]
8171
// - GetKeyIndex() [Internal]
8172
// - GetKeyName()
8173
// - GetKeyChordName() [Internal]
8174
// - CalcTypematicRepeatAmount() [Internal]
8175
// - GetTypematicRepeatRate() [Internal]
8176
// - GetKeyPressedAmount() [Internal]
8177
// - GetKeyMagnitude2d() [Internal]
8178
//-----------------------------------------------------------------------------
8179
// - UpdateKeyRoutingTable() [Internal]
8180
// - GetRoutingIdFromOwnerId() [Internal]
8181
// - GetShortcutRoutingData() [Internal]
8182
// - CalcRoutingScore() [Internal]
8183
// - SetShortcutRouting() [Internal]
8184
// - TestShortcutRouting() [Internal]
8185
//-----------------------------------------------------------------------------
8186
// - IsKeyDown()
8187
// - IsKeyPressed()
8188
// - IsKeyReleased()
8189
//-----------------------------------------------------------------------------
8190
// - IsMouseDown()
8191
// - IsMouseClicked()
8192
// - IsMouseReleased()
8193
// - IsMouseDoubleClicked()
8194
// - GetMouseClickedCount()
8195
// - IsMouseHoveringRect() [Internal]
8196
// - IsMouseDragPastThreshold() [Internal]
8197
// - IsMouseDragging()
8198
// - GetMousePos()
8199
// - GetMousePosOnOpeningCurrentPopup()
8200
// - IsMousePosValid()
8201
// - IsAnyMouseDown()
8202
// - GetMouseDragDelta()
8203
// - ResetMouseDragDelta()
8204
// - GetMouseCursor()
8205
// - SetMouseCursor()
8206
//-----------------------------------------------------------------------------
8207
// - UpdateAliasKey()
8208
// - GetMergedModsFromKeys()
8209
// - UpdateKeyboardInputs()
8210
// - UpdateMouseInputs()
8211
//-----------------------------------------------------------------------------
8212
// - LockWheelingWindow [Internal]
8213
// - FindBestWheelingWindow [Internal]
8214
// - UpdateMouseWheel() [Internal]
8215
//-----------------------------------------------------------------------------
8216
// - SetNextFrameWantCaptureKeyboard()
8217
// - SetNextFrameWantCaptureMouse()
8218
//-----------------------------------------------------------------------------
8219
// - GetInputSourceName() [Internal]
8220
// - DebugPrintInputEvent() [Internal]
8221
// - UpdateInputEvents() [Internal]
8222
//-----------------------------------------------------------------------------
8223
// - GetKeyOwner() [Internal]
8224
// - TestKeyOwner() [Internal]
8225
// - SetKeyOwner() [Internal]
8226
// - SetItemKeyOwner() [Internal]
8227
// - Shortcut() [Internal]
8228
//-----------------------------------------------------------------------------
8229
8230
ImGuiKeyData* ImGui::GetKeyData(ImGuiKey key)
8231
119k
{
8232
119k
    ImGuiContext& g = *GImGui;
8233
8234
    // Special storage location for mods
8235
119k
    if (key & ImGuiMod_Mask_)
8236
27.0k
        key = ConvertSingleModFlagToKey(key);
8237
8238
119k
    int index;
8239
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8240
    IM_ASSERT(key >= ImGuiKey_LegacyNativeKey_BEGIN && key < ImGuiKey_NamedKey_END);
8241
    if (IsLegacyKey(key))
8242
        index = (g.IO.KeyMap[key] != -1) ? g.IO.KeyMap[key] : key; // Remap native->imgui or imgui->native
8243
    else
8244
        index = key;
8245
#else
8246
119k
    IM_ASSERT(IsNamedKey(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend & user code.");
8247
119k
    index = key - ImGuiKey_NamedKey_BEGIN;
8248
119k
#endif
8249
119k
    return &g.IO.KeysData[index];
8250
119k
}
8251
8252
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8253
ImGuiKey ImGui::GetKeyIndex(ImGuiKey key)
8254
{
8255
    ImGuiContext& g = *GImGui;
8256
    IM_ASSERT(IsNamedKey(key));
8257
    const ImGuiKeyData* key_data = GetKeyData(key);
8258
    return (ImGuiKey)(key_data - g.IO.KeysData);
8259
}
8260
#endif
8261
8262
// Those names a provided for debugging purpose and are not meant to be saved persistently not compared.
8263
static const char* const GKeyNames[] =
8264
{
8265
    "Tab", "LeftArrow", "RightArrow", "UpArrow", "DownArrow", "PageUp", "PageDown",
8266
    "Home", "End", "Insert", "Delete", "Backspace", "Space", "Enter", "Escape",
8267
    "LeftCtrl", "LeftShift", "LeftAlt", "LeftSuper", "RightCtrl", "RightShift", "RightAlt", "RightSuper", "Menu",
8268
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
8269
    "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
8270
    "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
8271
    "Apostrophe", "Comma", "Minus", "Period", "Slash", "Semicolon", "Equal", "LeftBracket",
8272
    "Backslash", "RightBracket", "GraveAccent", "CapsLock", "ScrollLock", "NumLock", "PrintScreen",
8273
    "Pause", "Keypad0", "Keypad1", "Keypad2", "Keypad3", "Keypad4", "Keypad5", "Keypad6",
8274
    "Keypad7", "Keypad8", "Keypad9", "KeypadDecimal", "KeypadDivide", "KeypadMultiply",
8275
    "KeypadSubtract", "KeypadAdd", "KeypadEnter", "KeypadEqual",
8276
    "GamepadStart", "GamepadBack",
8277
    "GamepadFaceLeft", "GamepadFaceRight", "GamepadFaceUp", "GamepadFaceDown",
8278
    "GamepadDpadLeft", "GamepadDpadRight", "GamepadDpadUp", "GamepadDpadDown",
8279
    "GamepadL1", "GamepadR1", "GamepadL2", "GamepadR2", "GamepadL3", "GamepadR3",
8280
    "GamepadLStickLeft", "GamepadLStickRight", "GamepadLStickUp", "GamepadLStickDown",
8281
    "GamepadRStickLeft", "GamepadRStickRight", "GamepadRStickUp", "GamepadRStickDown",
8282
    "MouseLeft", "MouseRight", "MouseMiddle", "MouseX1", "MouseX2", "MouseWheelX", "MouseWheelY",
8283
    "ModCtrl", "ModShift", "ModAlt", "ModSuper", // ReservedForModXXX are showing the ModXXX names.
8284
};
8285
IM_STATIC_ASSERT(ImGuiKey_NamedKey_COUNT == IM_ARRAYSIZE(GKeyNames));
8286
8287
const char* ImGui::GetKeyName(ImGuiKey key)
8288
0
{
8289
0
#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
8290
0
    IM_ASSERT((IsNamedKey(key) || key == ImGuiKey_None) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend and user code.");
8291
#else
8292
    if (IsLegacyKey(key))
8293
    {
8294
        ImGuiIO& io = GetIO();
8295
        if (io.KeyMap[key] == -1)
8296
            return "N/A";
8297
        IM_ASSERT(IsNamedKey((ImGuiKey)io.KeyMap[key]));
8298
        key = (ImGuiKey)io.KeyMap[key];
8299
    }
8300
#endif
8301
0
    if (key == ImGuiKey_None)
8302
0
        return "None";
8303
0
    if (key & ImGuiMod_Mask_)
8304
0
        key = ConvertSingleModFlagToKey(key);
8305
0
    if (!IsNamedKey(key))
8306
0
        return "Unknown";
8307
8308
0
    return GKeyNames[key - ImGuiKey_NamedKey_BEGIN];
8309
0
}
8310
8311
// ImGuiMod_Shortcut is translated to either Ctrl or Super.
8312
void ImGui::GetKeyChordName(ImGuiKeyChord key_chord, char* out_buf, int out_buf_size)
8313
0
{
8314
0
    ImGuiContext& g = *GImGui;
8315
0
    if (key_chord & ImGuiMod_Shortcut)
8316
0
        key_chord = ConvertShortcutMod(key_chord);
8317
0
    ImFormatString(out_buf, (size_t)out_buf_size, "%s%s%s%s%s",
8318
0
        (key_chord & ImGuiMod_Ctrl) ? "Ctrl+" : "",
8319
0
        (key_chord & ImGuiMod_Shift) ? "Shift+" : "",
8320
0
        (key_chord & ImGuiMod_Alt) ? "Alt+" : "",
8321
0
        (key_chord & ImGuiMod_Super) ? (g.IO.ConfigMacOSXBehaviors ? "Cmd+" : "Super+") : "",
8322
0
        GetKeyName((ImGuiKey)(key_chord & ~ImGuiMod_Mask_)));
8323
0
}
8324
8325
// t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)
8326
// t1 = current time (e.g.: g.Time)
8327
// An event is triggered at:
8328
//  t = 0.0f     t = repeat_delay,    t = repeat_delay + repeat_rate*N
8329
int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)
8330
823
{
8331
823
    if (t1 == 0.0f)
8332
0
        return 1;
8333
823
    if (t0 >= t1)
8334
0
        return 0;
8335
823
    if (repeat_rate <= 0.0f)
8336
0
        return (t0 < repeat_delay) && (t1 >= repeat_delay);
8337
823
    const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);
8338
823
    const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);
8339
823
    const int count = count_t1 - count_t0;
8340
823
    return count;
8341
823
}
8342
8343
void ImGui::GetTypematicRepeatRate(ImGuiInputFlags flags, float* repeat_delay, float* repeat_rate)
8344
1.34k
{
8345
1.34k
    ImGuiContext& g = *GImGui;
8346
1.34k
    switch (flags & ImGuiInputFlags_RepeatRateMask_)
8347
1.34k
    {
8348
142
    case ImGuiInputFlags_RepeatRateNavMove:             *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.80f; return;
8349
0
    case ImGuiInputFlags_RepeatRateNavTweak:            *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.30f; return;
8350
1.20k
    case ImGuiInputFlags_RepeatRateDefault: default:    *repeat_delay = g.IO.KeyRepeatDelay * 1.00f; *repeat_rate = g.IO.KeyRepeatRate * 1.00f; return;
8351
1.34k
    }
8352
1.34k
}
8353
8354
// Return value representing the number of presses in the last time period, for the given repeat rate
8355
// (most often returns 0 or 1. The result is generally only >1 when RepeatRate is smaller than DeltaTime, aka large DeltaTime or fast RepeatRate)
8356
int ImGui::GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float repeat_rate)
8357
823
{
8358
823
    ImGuiContext& g = *GImGui;
8359
823
    const ImGuiKeyData* key_data = GetKeyData(key);
8360
823
    if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
8361
0
        return 0;
8362
823
    const float t = key_data->DownDuration;
8363
823
    return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate);
8364
823
}
8365
8366
// Return 2D vector representing the combination of four cardinal direction, with analog value support (for e.g. ImGuiKey_GamepadLStick* values).
8367
ImVec2 ImGui::GetKeyMagnitude2d(ImGuiKey key_left, ImGuiKey key_right, ImGuiKey key_up, ImGuiKey key_down)
8368
0
{
8369
0
    return ImVec2(
8370
0
        GetKeyData(key_right)->AnalogValue - GetKeyData(key_left)->AnalogValue,
8371
0
        GetKeyData(key_down)->AnalogValue - GetKeyData(key_up)->AnalogValue);
8372
0
}
8373
8374
// Rewrite routing data buffers to strip old entries + sort by key to make queries not touch scattered data.
8375
//   Entries   D,A,B,B,A,C,B     --> A,A,B,B,B,C,D
8376
//   Index     A:1 B:2 C:5 D:0   --> A:0 B:2 C:5 D:6
8377
// See 'Metrics->Key Owners & Shortcut Routing' to visualize the result of that operation.
8378
static void ImGui::UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt)
8379
3.00k
{
8380
3.00k
    ImGuiContext& g = *GImGui;
8381
3.00k
    rt->EntriesNext.resize(0);
8382
423k
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
8383
420k
    {
8384
420k
        const int new_routing_start_idx = rt->EntriesNext.Size;
8385
420k
        ImGuiKeyRoutingData* routing_entry;
8386
420k
        for (int old_routing_idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; old_routing_idx != -1; old_routing_idx = routing_entry->NextEntryIndex)
8387
0
        {
8388
0
            routing_entry = &rt->Entries[old_routing_idx];
8389
0
            routing_entry->RoutingCurr = routing_entry->RoutingNext; // Update entry
8390
0
            routing_entry->RoutingNext = ImGuiKeyOwner_None;
8391
0
            routing_entry->RoutingNextScore = 255;
8392
0
            if (routing_entry->RoutingCurr == ImGuiKeyOwner_None)
8393
0
                continue;
8394
0
            rt->EntriesNext.push_back(*routing_entry); // Write alive ones into new buffer
8395
8396
            // Apply routing to owner if there's no owner already (RoutingCurr == None at this point)
8397
0
            if (routing_entry->Mods == g.IO.KeyMods)
8398
0
            {
8399
0
                ImGuiKeyOwnerData* owner_data = ImGui::GetKeyOwnerData(key);
8400
0
                if (owner_data->OwnerCurr == ImGuiKeyOwner_None)
8401
0
                    owner_data->OwnerCurr = routing_entry->RoutingCurr;
8402
0
            }
8403
0
        }
8404
8405
        // Rewrite linked-list
8406
420k
        rt->Index[key - ImGuiKey_NamedKey_BEGIN] = (ImGuiKeyRoutingIndex)(new_routing_start_idx < rt->EntriesNext.Size ? new_routing_start_idx : -1);
8407
420k
        for (int n = new_routing_start_idx; n < rt->EntriesNext.Size; n++)
8408
0
            rt->EntriesNext[n].NextEntryIndex = (ImGuiKeyRoutingIndex)((n + 1 < rt->EntriesNext.Size) ? n + 1 : -1);
8409
420k
    }
8410
3.00k
    rt->Entries.swap(rt->EntriesNext); // Swap new and old indexes
8411
3.00k
}
8412
8413
// owner_id may be None/Any, but routing_id needs to be always be set, so we default to GetCurrentFocusScope().
8414
static inline ImGuiID GetRoutingIdFromOwnerId(ImGuiID owner_id)
8415
0
{
8416
0
    ImGuiContext& g = *GImGui;
8417
0
    return (owner_id != ImGuiKeyOwner_None && owner_id != ImGuiKeyOwner_Any) ? owner_id : g.CurrentFocusScopeId;
8418
0
}
8419
8420
ImGuiKeyRoutingData* ImGui::GetShortcutRoutingData(ImGuiKeyChord key_chord)
8421
0
{
8422
    // Majority of shortcuts will be Key + any number of Mods
8423
    // We accept _Single_ mod with ImGuiKey_None.
8424
    //  - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl);                    // Legal
8425
    //  - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl | ImGuiMod_Shift);   // Legal
8426
    //  - Shortcut(ImGuiMod_Ctrl);                                 // Legal
8427
    //  - Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift);                // Not legal
8428
0
    ImGuiContext& g = *GImGui;
8429
0
    ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
8430
0
    ImGuiKeyRoutingData* routing_data;
8431
0
    if (key_chord & ImGuiMod_Shortcut)
8432
0
        key_chord = ConvertShortcutMod(key_chord);
8433
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
8434
0
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
8435
0
    if (key == ImGuiKey_None)
8436
0
        key = ConvertSingleModFlagToKey(mods);
8437
0
    IM_ASSERT(IsNamedKey(key));
8438
8439
    // Get (in the majority of case, the linked list will have one element so this should be 2 reads.
8440
    // Subsequent elements will be contiguous in memory as list is sorted/rebuilt in NewFrame).
8441
0
    for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; idx = routing_data->NextEntryIndex)
8442
0
    {
8443
0
        routing_data = &rt->Entries[idx];
8444
0
        if (routing_data->Mods == mods)
8445
0
            return routing_data;
8446
0
    }
8447
8448
    // Add to linked-list
8449
0
    ImGuiKeyRoutingIndex routing_data_idx = (ImGuiKeyRoutingIndex)rt->Entries.Size;
8450
0
    rt->Entries.push_back(ImGuiKeyRoutingData());
8451
0
    routing_data = &rt->Entries[routing_data_idx];
8452
0
    routing_data->Mods = (ImU16)mods;
8453
0
    routing_data->NextEntryIndex = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; // Setup linked list
8454
0
    rt->Index[key - ImGuiKey_NamedKey_BEGIN] = routing_data_idx;
8455
0
    return routing_data;
8456
0
}
8457
8458
// Current score encoding (lower is highest priority):
8459
//  -   0: ImGuiInputFlags_RouteGlobalHigh
8460
//  -   1: ImGuiInputFlags_RouteFocused (if item active)
8461
//  -   2: ImGuiInputFlags_RouteGlobal
8462
//  -  3+: ImGuiInputFlags_RouteFocused (if window in focus-stack)
8463
//  - 254: ImGuiInputFlags_RouteGlobalLow
8464
//  - 255: never route
8465
// 'flags' should include an explicit routing policy
8466
static int CalcRoutingScore(ImGuiWindow* location, ImGuiID owner_id, ImGuiInputFlags flags)
8467
0
{
8468
0
    if (flags & ImGuiInputFlags_RouteFocused)
8469
0
    {
8470
0
        ImGuiContext& g = *GImGui;
8471
0
        ImGuiWindow* focused = g.NavWindow;
8472
8473
        // ActiveID gets top priority
8474
        // (we don't check g.ActiveIdUsingAllKeys here. Routing is applied but if input ownership is tested later it may discard it)
8475
0
        if (owner_id != 0 && g.ActiveId == owner_id)
8476
0
            return 1;
8477
8478
        // Score based on distance to focused window (lower is better)
8479
        // Assuming both windows are submitting a routing request,
8480
        // - When Window....... is focused -> Window scores 3 (best), Window/ChildB scores 255 (no match)
8481
        // - When Window/ChildB is focused -> Window scores 4,        Window/ChildB scores 3 (best)
8482
        // Assuming only WindowA is submitting a routing request,
8483
        // - When Window/ChildB is focused -> Window scores 4 (best), Window/ChildB doesn't have a score.
8484
0
        if (focused != NULL && focused->RootWindow == location->RootWindow)
8485
0
            for (int next_score = 3; focused != NULL; next_score++)
8486
0
            {
8487
0
                if (focused == location)
8488
0
                {
8489
0
                    IM_ASSERT(next_score < 255);
8490
0
                    return next_score;
8491
0
                }
8492
0
                focused = (focused->RootWindow != focused) ? focused->ParentWindow : NULL; // FIXME: This could be later abstracted as a focus path
8493
0
            }
8494
0
        return 255;
8495
0
    }
8496
8497
    // ImGuiInputFlags_RouteGlobalHigh is default, so calls without flags are not conditional
8498
0
    if (flags & ImGuiInputFlags_RouteGlobal)
8499
0
        return 2;
8500
0
    if (flags & ImGuiInputFlags_RouteGlobalLow)
8501
0
        return 254;
8502
0
    return 0;
8503
0
}
8504
8505
// Request a desired route for an input chord (key + mods).
8506
// Return true if the route is available this frame.
8507
// - Routes and key ownership are attributed at the beginning of next frame based on best score and mod state.
8508
//   (Conceptually this does a "Submit for next frame" + "Test for current frame".
8509
//   As such, it could be called TrySetXXX or SubmitXXX, or the Submit and Test operations should be separate.)
8510
// - Using 'owner_id == ImGuiKeyOwner_Any/0': auto-assign an owner based on current focus scope (each window has its focus scope by default)
8511
// - Using 'owner_id == ImGuiKeyOwner_None': allows disabling/locking a shortcut.
8512
bool ImGui::SetShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
8513
6.00k
{
8514
6.00k
    ImGuiContext& g = *GImGui;
8515
6.00k
    if ((flags & ImGuiInputFlags_RouteMask_) == 0)
8516
0
        flags |= ImGuiInputFlags_RouteGlobalHigh; // IMPORTANT: This is the default for SetShortcutRouting() but NOT Shortcut()
8517
6.00k
    else
8518
6.00k
        IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiInputFlags_RouteMask_)); // Check that only 1 routing flag is used
8519
8520
6.00k
    if (flags & ImGuiInputFlags_RouteUnlessBgFocused)
8521
0
        if (g.NavWindow == NULL)
8522
0
            return false;
8523
6.00k
    if (flags & ImGuiInputFlags_RouteAlways)
8524
6.00k
        return true;
8525
8526
0
    const int score = CalcRoutingScore(g.CurrentWindow, owner_id, flags);
8527
0
    if (score == 255)
8528
0
        return false;
8529
8530
    // Submit routing for NEXT frame (assuming score is sufficient)
8531
    // FIXME: Could expose a way to use a "serve last" policy for same score resolution (using <= instead of <).
8532
0
    ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord);
8533
0
    const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
8534
    //const bool set_route = (flags & ImGuiInputFlags_ServeLast) ? (score <= routing_data->RoutingNextScore) : (score < routing_data->RoutingNextScore);
8535
0
    if (score < routing_data->RoutingNextScore)
8536
0
    {
8537
0
        routing_data->RoutingNext = routing_id;
8538
0
        routing_data->RoutingNextScore = (ImU8)score;
8539
0
    }
8540
8541
    // Return routing state for CURRENT frame
8542
0
    return routing_data->RoutingCurr == routing_id;
8543
0
}
8544
8545
// Currently unused by core (but used by tests)
8546
// Note: this cannot be turned into GetShortcutRouting() because we do the owner_id->routing_id translation, name would be more misleading.
8547
bool ImGui::TestShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id)
8548
0
{
8549
0
    const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
8550
0
    ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord); // FIXME: Could avoid creating entry.
8551
0
    return routing_data->RoutingCurr == routing_id;
8552
0
}
8553
8554
// Note that Dear ImGui doesn't know the meaning/semantic of ImGuiKey from 0..511: they are legacy native keycodes.
8555
// Consider transitioning from 'IsKeyDown(MY_ENGINE_KEY_A)' (<1.87) to IsKeyDown(ImGuiKey_A) (>= 1.87)
8556
bool ImGui::IsKeyDown(ImGuiKey key)
8557
45.0k
{
8558
45.0k
    return IsKeyDown(key, ImGuiKeyOwner_Any);
8559
45.0k
}
8560
8561
bool ImGui::IsKeyDown(ImGuiKey key, ImGuiID owner_id)
8562
49.1k
{
8563
49.1k
    const ImGuiKeyData* key_data = GetKeyData(key);
8564
49.1k
    if (!key_data->Down)
8565
48.8k
        return false;
8566
270
    if (!TestKeyOwner(key, owner_id))
8567
0
        return false;
8568
270
    return true;
8569
270
}
8570
8571
bool ImGui::IsKeyPressed(ImGuiKey key, bool repeat)
8572
27.6k
{
8573
27.6k
    return IsKeyPressed(key, ImGuiKeyOwner_Any, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None);
8574
27.6k
}
8575
8576
// Important: unless legacy IsKeyPressed(ImGuiKey, bool repeat=true) which DEFAULT to repeat, this requires EXPLICIT repeat.
8577
bool ImGui::IsKeyPressed(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
8578
48.2k
{
8579
48.2k
    const ImGuiKeyData* key_data = GetKeyData(key);
8580
48.2k
    if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
8581
46.8k
        return false;
8582
1.37k
    const float t = key_data->DownDuration;
8583
1.37k
    if (t < 0.0f)
8584
0
        return false;
8585
1.37k
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
8586
8587
1.37k
    bool pressed = (t == 0.0f);
8588
1.37k
    if (!pressed && ((flags & ImGuiInputFlags_Repeat) != 0))
8589
1.34k
    {
8590
1.34k
        float repeat_delay, repeat_rate;
8591
1.34k
        GetTypematicRepeatRate(flags, &repeat_delay, &repeat_rate);
8592
1.34k
        pressed = (t > repeat_delay) && GetKeyPressedAmount(key, repeat_delay, repeat_rate) > 0;
8593
1.34k
    }
8594
1.37k
    if (!pressed)
8595
1.03k
        return false;
8596
337
    if (!TestKeyOwner(key, owner_id))
8597
0
        return false;
8598
337
    return true;
8599
337
}
8600
8601
bool ImGui::IsKeyReleased(ImGuiKey key)
8602
0
{
8603
0
    return IsKeyReleased(key, ImGuiKeyOwner_Any);
8604
0
}
8605
8606
bool ImGui::IsKeyReleased(ImGuiKey key, ImGuiID owner_id)
8607
0
{
8608
0
    const ImGuiKeyData* key_data = GetKeyData(key);
8609
0
    if (key_data->DownDurationPrev < 0.0f || key_data->Down)
8610
0
        return false;
8611
0
    if (!TestKeyOwner(key, owner_id))
8612
0
        return false;
8613
0
    return true;
8614
0
}
8615
8616
bool ImGui::IsMouseDown(ImGuiMouseButton button)
8617
0
{
8618
0
    ImGuiContext& g = *GImGui;
8619
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8620
0
    return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // should be same as IsKeyDown(MouseButtonToKey(button), ImGuiKeyOwner_Any), but this allows legacy code hijacking the io.Mousedown[] array.
8621
0
}
8622
8623
bool ImGui::IsMouseDown(ImGuiMouseButton button, ImGuiID owner_id)
8624
0
{
8625
0
    ImGuiContext& g = *GImGui;
8626
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8627
0
    return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyDown(MouseButtonToKey(button), owner_id), but this allows legacy code hijacking the io.Mousedown[] array.
8628
0
}
8629
8630
bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)
8631
0
{
8632
0
    return IsMouseClicked(button, ImGuiKeyOwner_Any, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None);
8633
0
}
8634
8635
bool ImGui::IsMouseClicked(ImGuiMouseButton button, ImGuiID owner_id, ImGuiInputFlags flags)
8636
0
{
8637
0
    ImGuiContext& g = *GImGui;
8638
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8639
0
    if (!g.IO.MouseDown[button]) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
8640
0
        return false;
8641
0
    const float t = g.IO.MouseDownDuration[button];
8642
0
    if (t < 0.0f)
8643
0
        return false;
8644
0
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
8645
8646
0
    const bool repeat = (flags & ImGuiInputFlags_Repeat) != 0;
8647
0
    const bool pressed = (t == 0.0f) || (repeat && t > g.IO.KeyRepeatDelay && CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0);
8648
0
    if (!pressed)
8649
0
        return false;
8650
8651
0
    if (!TestKeyOwner(MouseButtonToKey(button), owner_id))
8652
0
        return false;
8653
8654
0
    return true;
8655
0
}
8656
8657
bool ImGui::IsMouseReleased(ImGuiMouseButton button)
8658
0
{
8659
0
    ImGuiContext& g = *GImGui;
8660
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8661
0
    return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // Should be same as IsKeyReleased(MouseButtonToKey(button), ImGuiKeyOwner_Any)
8662
0
}
8663
8664
bool ImGui::IsMouseReleased(ImGuiMouseButton button, ImGuiID owner_id)
8665
0
{
8666
0
    ImGuiContext& g = *GImGui;
8667
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8668
0
    return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyReleased(MouseButtonToKey(button), owner_id)
8669
0
}
8670
8671
bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
8672
0
{
8673
0
    ImGuiContext& g = *GImGui;
8674
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8675
0
    return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any);
8676
0
}
8677
8678
int ImGui::GetMouseClickedCount(ImGuiMouseButton button)
8679
0
{
8680
0
    ImGuiContext& g = *GImGui;
8681
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8682
0
    return g.IO.MouseClickedCount[button];
8683
0
}
8684
8685
// Test if mouse cursor is hovering given rectangle
8686
// NB- Rectangle is clipped by our current clip setting
8687
// NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
8688
bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
8689
24.4k
{
8690
24.4k
    ImGuiContext& g = *GImGui;
8691
8692
    // Clip
8693
24.4k
    ImRect rect_clipped(r_min, r_max);
8694
24.4k
    if (clip)
8695
15.4k
        rect_clipped.ClipWith(g.CurrentWindow->ClipRect);
8696
8697
    // Expand for touch input
8698
24.4k
    const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding);
8699
24.4k
    if (!rect_for_touch.Contains(g.IO.MousePos))
8700
24.4k
        return false;
8701
20
    if (!g.MouseViewport->GetMainRect().Overlaps(rect_clipped))
8702
0
        return false;
8703
20
    return true;
8704
20
}
8705
8706
// Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame.
8707
// [Internal] This doesn't test if the button is pressed
8708
bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)
8709
0
{
8710
0
    ImGuiContext& g = *GImGui;
8711
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8712
0
    if (lock_threshold < 0.0f)
8713
0
        lock_threshold = g.IO.MouseDragThreshold;
8714
0
    return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
8715
0
}
8716
8717
bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
8718
0
{
8719
0
    ImGuiContext& g = *GImGui;
8720
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8721
0
    if (!g.IO.MouseDown[button])
8722
0
        return false;
8723
0
    return IsMouseDragPastThreshold(button, lock_threshold);
8724
0
}
8725
8726
ImVec2 ImGui::GetMousePos()
8727
1.51k
{
8728
1.51k
    ImGuiContext& g = *GImGui;
8729
1.51k
    return g.IO.MousePos;
8730
1.51k
}
8731
8732
// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
8733
ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
8734
0
{
8735
0
    ImGuiContext& g = *GImGui;
8736
0
    if (g.BeginPopupStack.Size > 0)
8737
0
        return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos;
8738
0
    return g.IO.MousePos;
8739
0
}
8740
8741
// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
8742
bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
8743
12.4k
{
8744
    // The assert is only to silence a false-positive in XCode Static Analysis.
8745
    // Because GImGui is not dereferenced in every code path, the static analyzer assume that it may be NULL (which it doesn't for other functions).
8746
12.4k
    IM_ASSERT(GImGui != NULL);
8747
12.4k
    const float MOUSE_INVALID = -256000.0f;
8748
12.4k
    ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
8749
12.4k
    return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
8750
12.4k
}
8751
8752
// [WILL OBSOLETE] This was designed for backends, but prefer having backend maintain a mask of held mouse buttons, because upcoming input queue system will make this invalid.
8753
bool ImGui::IsAnyMouseDown()
8754
0
{
8755
0
    ImGuiContext& g = *GImGui;
8756
0
    for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
8757
0
        if (g.IO.MouseDown[n])
8758
0
            return true;
8759
0
    return false;
8760
0
}
8761
8762
// Return the delta from the initial clicking position while the mouse button is clicked or was just released.
8763
// This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
8764
// NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window.
8765
ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)
8766
0
{
8767
0
    ImGuiContext& g = *GImGui;
8768
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8769
0
    if (lock_threshold < 0.0f)
8770
0
        lock_threshold = g.IO.MouseDragThreshold;
8771
0
    if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
8772
0
        if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
8773
0
            if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button]))
8774
0
                return g.IO.MousePos - g.IO.MouseClickedPos[button];
8775
0
    return ImVec2(0.0f, 0.0f);
8776
0
}
8777
8778
void ImGui::ResetMouseDragDelta(ImGuiMouseButton button)
8779
0
{
8780
0
    ImGuiContext& g = *GImGui;
8781
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8782
    // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
8783
0
    g.IO.MouseClickedPos[button] = g.IO.MousePos;
8784
0
}
8785
8786
// Get desired mouse cursor shape.
8787
// Important: this is meant to be used by a platform backend, it is reset in ImGui::NewFrame(),
8788
// updated during the frame, and locked in EndFrame()/Render().
8789
// If you use software rendering by setting io.MouseDrawCursor then Dear ImGui will render those for you
8790
ImGuiMouseCursor ImGui::GetMouseCursor()
8791
0
{
8792
0
    ImGuiContext& g = *GImGui;
8793
0
    return g.MouseCursor;
8794
0
}
8795
8796
void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
8797
0
{
8798
0
    ImGuiContext& g = *GImGui;
8799
0
    g.MouseCursor = cursor_type;
8800
0
}
8801
8802
static void UpdateAliasKey(ImGuiKey key, bool v, float analog_value)
8803
21.0k
{
8804
21.0k
    IM_ASSERT(ImGui::IsAliasKey(key));
8805
21.0k
    ImGuiKeyData* key_data = ImGui::GetKeyData(key);
8806
21.0k
    key_data->Down = v;
8807
21.0k
    key_data->AnalogValue = analog_value;
8808
21.0k
}
8809
8810
// [Internal] Do not use directly
8811
static ImGuiKeyChord GetMergedModsFromKeys()
8812
6.00k
{
8813
6.00k
    ImGuiKeyChord mods = 0;
8814
6.00k
    if (ImGui::IsKeyDown(ImGuiMod_Ctrl))     { mods |= ImGuiMod_Ctrl; }
8815
6.00k
    if (ImGui::IsKeyDown(ImGuiMod_Shift))    { mods |= ImGuiMod_Shift; }
8816
6.00k
    if (ImGui::IsKeyDown(ImGuiMod_Alt))      { mods |= ImGuiMod_Alt; }
8817
6.00k
    if (ImGui::IsKeyDown(ImGuiMod_Super))    { mods |= ImGuiMod_Super; }
8818
6.00k
    return mods;
8819
6.00k
}
8820
8821
static void ImGui::UpdateKeyboardInputs()
8822
3.00k
{
8823
3.00k
    ImGuiContext& g = *GImGui;
8824
3.00k
    ImGuiIO& io = g.IO;
8825
8826
    // Import legacy keys or verify they are not used
8827
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8828
    if (io.BackendUsingLegacyKeyArrays == 0)
8829
    {
8830
        // Backend used new io.AddKeyEvent() API: Good! Verify that old arrays are never written to externally.
8831
        for (int n = 0; n < ImGuiKey_LegacyNativeKey_END; n++)
8832
            IM_ASSERT((io.KeysDown[n] == false || IsKeyDown((ImGuiKey)n)) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
8833
    }
8834
    else
8835
    {
8836
        if (g.FrameCount == 0)
8837
            for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
8838
                IM_ASSERT(g.IO.KeyMap[n] == -1 && "Backend is not allowed to write to io.KeyMap[0..511]!");
8839
8840
        // Build reverse KeyMap (Named -> Legacy)
8841
        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
8842
            if (io.KeyMap[n] != -1)
8843
            {
8844
                IM_ASSERT(IsLegacyKey((ImGuiKey)io.KeyMap[n]));
8845
                io.KeyMap[io.KeyMap[n]] = n;
8846
            }
8847
8848
        // Import legacy keys into new ones
8849
        for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
8850
            if (io.KeysDown[n] || io.BackendUsingLegacyKeyArrays == 1)
8851
            {
8852
                const ImGuiKey key = (ImGuiKey)(io.KeyMap[n] != -1 ? io.KeyMap[n] : n);
8853
                IM_ASSERT(io.KeyMap[n] == -1 || IsNamedKey(key));
8854
                io.KeysData[key].Down = io.KeysDown[n];
8855
                if (key != n)
8856
                    io.KeysDown[key] = io.KeysDown[n]; // Allow legacy code using io.KeysDown[GetKeyIndex()] with old backends
8857
                io.BackendUsingLegacyKeyArrays = 1;
8858
            }
8859
        if (io.BackendUsingLegacyKeyArrays == 1)
8860
        {
8861
            GetKeyData(ImGuiMod_Ctrl)->Down = io.KeyCtrl;
8862
            GetKeyData(ImGuiMod_Shift)->Down = io.KeyShift;
8863
            GetKeyData(ImGuiMod_Alt)->Down = io.KeyAlt;
8864
            GetKeyData(ImGuiMod_Super)->Down = io.KeySuper;
8865
        }
8866
    }
8867
8868
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8869
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
8870
    if (io.BackendUsingLegacyNavInputArray && nav_gamepad_active)
8871
    {
8872
        #define MAP_LEGACY_NAV_INPUT_TO_KEY1(_KEY, _NAV1)           do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f); io.KeysData[_KEY].AnalogValue = io.NavInputs[_NAV1]; } while (0)
8873
        #define MAP_LEGACY_NAV_INPUT_TO_KEY2(_KEY, _NAV1, _NAV2)    do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f) || (io.NavInputs[_NAV2] > 0.0f); io.KeysData[_KEY].AnalogValue = ImMax(io.NavInputs[_NAV1], io.NavInputs[_NAV2]); } while (0)
8874
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceDown, ImGuiNavInput_Activate);
8875
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceRight, ImGuiNavInput_Cancel);
8876
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceLeft, ImGuiNavInput_Menu);
8877
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceUp, ImGuiNavInput_Input);
8878
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadLeft, ImGuiNavInput_DpadLeft);
8879
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadRight, ImGuiNavInput_DpadRight);
8880
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadUp, ImGuiNavInput_DpadUp);
8881
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadDown, ImGuiNavInput_DpadDown);
8882
        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadL1, ImGuiNavInput_FocusPrev, ImGuiNavInput_TweakSlow);
8883
        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadR1, ImGuiNavInput_FocusNext, ImGuiNavInput_TweakFast);
8884
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickLeft, ImGuiNavInput_LStickLeft);
8885
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickRight, ImGuiNavInput_LStickRight);
8886
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickUp, ImGuiNavInput_LStickUp);
8887
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickDown, ImGuiNavInput_LStickDown);
8888
        #undef NAV_MAP_KEY
8889
    }
8890
#endif
8891
#endif
8892
8893
    // Update aliases
8894
18.0k
    for (int n = 0; n < ImGuiMouseButton_COUNT; n++)
8895
15.0k
        UpdateAliasKey(MouseButtonToKey(n), io.MouseDown[n], io.MouseDown[n] ? 1.0f : 0.0f);
8896
3.00k
    UpdateAliasKey(ImGuiKey_MouseWheelX, io.MouseWheelH != 0.0f, io.MouseWheelH);
8897
3.00k
    UpdateAliasKey(ImGuiKey_MouseWheelY, io.MouseWheel != 0.0f, io.MouseWheel);
8898
8899
    // Synchronize io.KeyMods and io.KeyXXX values.
8900
    // - New backends (1.87+): send io.AddKeyEvent(ImGuiMod_XXX) ->                                      -> (here) deriving io.KeyMods + io.KeyXXX from key array.
8901
    // - Legacy backends:      set io.KeyXXX bools               -> (above) set key array from io.KeyXXX -> (here) deriving io.KeyMods + io.KeyXXX from key array.
8902
    // So with legacy backends the 4 values will do a unnecessary back-and-forth but it makes the code simpler and future facing.
8903
3.00k
    io.KeyMods = GetMergedModsFromKeys();
8904
3.00k
    io.KeyCtrl = (io.KeyMods & ImGuiMod_Ctrl) != 0;
8905
3.00k
    io.KeyShift = (io.KeyMods & ImGuiMod_Shift) != 0;
8906
3.00k
    io.KeyAlt = (io.KeyMods & ImGuiMod_Alt) != 0;
8907
3.00k
    io.KeySuper = (io.KeyMods & ImGuiMod_Super) != 0;
8908
8909
    // Clear gamepad data if disabled
8910
3.00k
    if ((io.BackendFlags & ImGuiBackendFlags_HasGamepad) == 0)
8911
75.0k
        for (int i = ImGuiKey_Gamepad_BEGIN; i < ImGuiKey_Gamepad_END; i++)
8912
72.0k
        {
8913
72.0k
            io.KeysData[i - ImGuiKey_KeysData_OFFSET].Down = false;
8914
72.0k
            io.KeysData[i - ImGuiKey_KeysData_OFFSET].AnalogValue = 0.0f;
8915
72.0k
        }
8916
8917
    // Update keys
8918
423k
    for (int i = 0; i < ImGuiKey_KeysData_SIZE; i++)
8919
420k
    {
8920
420k
        ImGuiKeyData* key_data = &io.KeysData[i];
8921
420k
        key_data->DownDurationPrev = key_data->DownDuration;
8922
420k
        key_data->DownDuration = key_data->Down ? (key_data->DownDuration < 0.0f ? 0.0f : key_data->DownDuration + io.DeltaTime) : -1.0f;
8923
420k
    }
8924
8925
    // Update keys/input owner (named keys only): one entry per key
8926
423k
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
8927
420k
    {
8928
420k
        ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_KeysData_OFFSET];
8929
420k
        ImGuiKeyOwnerData* owner_data = &g.KeysOwnerData[key - ImGuiKey_NamedKey_BEGIN];
8930
420k
        owner_data->OwnerCurr = owner_data->OwnerNext;
8931
420k
        if (!key_data->Down) // Important: ownership is released on the frame after a release. Ensure a 'MouseDown -> CloseWindow -> MouseUp' chain doesn't lead to someone else seeing the MouseUp.
8932
417k
            owner_data->OwnerNext = ImGuiKeyOwner_None;
8933
420k
        owner_data->LockThisFrame = owner_data->LockUntilRelease = owner_data->LockUntilRelease && key_data->Down;  // Clear LockUntilRelease when key is not Down anymore
8934
420k
    }
8935
8936
3.00k
    UpdateKeyRoutingTable(&g.KeysRoutingTable);
8937
3.00k
}
8938
8939
static void ImGui::UpdateMouseInputs()
8940
3.00k
{
8941
3.00k
    ImGuiContext& g = *GImGui;
8942
3.00k
    ImGuiIO& io = g.IO;
8943
8944
    // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
8945
3.00k
    if (IsMousePosValid(&io.MousePos))
8946
1.51k
        io.MousePos = g.MouseLastValidPos = ImFloorSigned(io.MousePos);
8947
8948
    // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
8949
3.00k
    if (IsMousePosValid(&io.MousePos) && IsMousePosValid(&io.MousePosPrev))
8950
1.46k
        io.MouseDelta = io.MousePos - io.MousePosPrev;
8951
1.53k
    else
8952
1.53k
        io.MouseDelta = ImVec2(0.0f, 0.0f);
8953
8954
    // If mouse moved we re-enable mouse hovering in case it was disabled by gamepad/keyboard. In theory should use a >0.0f threshold but would need to reset in everywhere we set this to true.
8955
3.00k
    if (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)
8956
108
        g.NavDisableMouseHover = false;
8957
8958
3.00k
    io.MousePosPrev = io.MousePos;
8959
18.0k
    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
8960
15.0k
    {
8961
15.0k
        io.MouseClicked[i] = io.MouseDown[i] && io.MouseDownDuration[i] < 0.0f;
8962
15.0k
        io.MouseClickedCount[i] = 0; // Will be filled below
8963
15.0k
        io.MouseReleased[i] = !io.MouseDown[i] && io.MouseDownDuration[i] >= 0.0f;
8964
15.0k
        io.MouseDownDurationPrev[i] = io.MouseDownDuration[i];
8965
15.0k
        io.MouseDownDuration[i] = io.MouseDown[i] ? (io.MouseDownDuration[i] < 0.0f ? 0.0f : io.MouseDownDuration[i] + io.DeltaTime) : -1.0f;
8966
15.0k
        if (io.MouseClicked[i])
8967
394
        {
8968
394
            bool is_repeated_click = false;
8969
394
            if ((float)(g.Time - io.MouseClickedTime[i]) < io.MouseDoubleClickTime)
8970
315
            {
8971
315
                ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
8972
315
                if (ImLengthSqr(delta_from_click_pos) < io.MouseDoubleClickMaxDist * io.MouseDoubleClickMaxDist)
8973
301
                    is_repeated_click = true;
8974
315
            }
8975
394
            if (is_repeated_click)
8976
301
                io.MouseClickedLastCount[i]++;
8977
93
            else
8978
93
                io.MouseClickedLastCount[i] = 1;
8979
394
            io.MouseClickedTime[i] = g.Time;
8980
394
            io.MouseClickedPos[i] = io.MousePos;
8981
394
            io.MouseClickedCount[i] = io.MouseClickedLastCount[i];
8982
394
            io.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
8983
394
            io.MouseDragMaxDistanceSqr[i] = 0.0f;
8984
394
        }
8985
14.6k
        else if (io.MouseDown[i])
8986
1.65k
        {
8987
            // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
8988
1.65k
            ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
8989
1.65k
            io.MouseDragMaxDistanceSqr[i] = ImMax(io.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos));
8990
1.65k
            io.MouseDragMaxDistanceAbs[i].x = ImMax(io.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x);
8991
1.65k
            io.MouseDragMaxDistanceAbs[i].y = ImMax(io.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y);
8992
1.65k
        }
8993
8994
        // We provide io.MouseDoubleClicked[] as a legacy service
8995
15.0k
        io.MouseDoubleClicked[i] = (io.MouseClickedCount[i] == 2);
8996
8997
        // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
8998
15.0k
        if (io.MouseClicked[i])
8999
394
            g.NavDisableMouseHover = false;
9000
15.0k
    }
9001
3.00k
}
9002
9003
static void LockWheelingWindow(ImGuiWindow* window, float wheel_amount)
9004
0
{
9005
0
    ImGuiContext& g = *GImGui;
9006
0
    if (window)
9007
0
        g.WheelingWindowReleaseTimer = ImMin(g.WheelingWindowReleaseTimer + ImAbs(wheel_amount) * WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER, WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER);
9008
0
    else
9009
0
        g.WheelingWindowReleaseTimer = 0.0f;
9010
0
    if (g.WheelingWindow == window)
9011
0
        return;
9012
0
    IMGUI_DEBUG_LOG_IO("LockWheelingWindow() \"%s\"\n", window ? window->Name : "NULL");
9013
0
    g.WheelingWindow = window;
9014
0
    g.WheelingWindowRefMousePos = g.IO.MousePos;
9015
0
    if (window == NULL)
9016
0
    {
9017
0
        g.WheelingWindowStartFrame = -1;
9018
0
        g.WheelingAxisAvg = ImVec2(0.0f, 0.0f);
9019
0
    }
9020
0
}
9021
9022
static ImGuiWindow* FindBestWheelingWindow(const ImVec2& wheel)
9023
0
{
9024
    // For each axis, find window in the hierarchy that may want to use scrolling
9025
0
    ImGuiContext& g = *GImGui;
9026
0
    ImGuiWindow* windows[2] = { NULL, NULL };
9027
0
    for (int axis = 0; axis < 2; axis++)
9028
0
        if (wheel[axis] != 0.0f)
9029
0
            for (ImGuiWindow* window = windows[axis] = g.HoveredWindow; window->Flags & ImGuiWindowFlags_ChildWindow; window = windows[axis] = window->ParentWindow)
9030
0
            {
9031
                // Bubble up into parent window if:
9032
                // - a child window doesn't allow any scrolling.
9033
                // - a child window has the ImGuiWindowFlags_NoScrollWithMouse flag.
9034
                //// - a child window doesn't need scrolling because it is already at the edge for the direction we are going in (FIXME-WIP)
9035
0
                const bool has_scrolling = (window->ScrollMax[axis] != 0.0f);
9036
0
                const bool inputs_disabled = (window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs);
9037
                //const bool scrolling_past_limits = (wheel_v < 0.0f) ? (window->Scroll[axis] <= 0.0f) : (window->Scroll[axis] >= window->ScrollMax[axis]);
9038
0
                if (has_scrolling && !inputs_disabled) // && !scrolling_past_limits)
9039
0
                    break; // select this window
9040
0
            }
9041
0
    if (windows[0] == NULL && windows[1] == NULL)
9042
0
        return NULL;
9043
9044
    // If there's only one window or only one axis then there's no ambiguity
9045
0
    if (windows[0] == windows[1] || windows[0] == NULL || windows[1] == NULL)
9046
0
        return windows[1] ? windows[1] : windows[0];
9047
9048
    // If candidate are different windows we need to decide which one to prioritize
9049
    // - First frame: only find a winner if one axis is zero.
9050
    // - Subsequent frames: only find a winner when one is more than the other.
9051
0
    if (g.WheelingWindowStartFrame == -1)
9052
0
        g.WheelingWindowStartFrame = g.FrameCount;
9053
0
    if ((g.WheelingWindowStartFrame == g.FrameCount && wheel.x != 0.0f && wheel.y != 0.0f) || (g.WheelingAxisAvg.x == g.WheelingAxisAvg.y))
9054
0
    {
9055
0
        g.WheelingWindowWheelRemainder = wheel;
9056
0
        return NULL;
9057
0
    }
9058
0
    return (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? windows[0] : windows[1];
9059
0
}
9060
9061
// Called by NewFrame()
9062
void ImGui::UpdateMouseWheel()
9063
3.00k
{
9064
    // Reset the locked window if we move the mouse or after the timer elapses.
9065
    // FIXME: Ideally we could refactor to have one timer for "changing window w/ same axis" and a shorter timer for "changing window or axis w/ other axis" (#3795)
9066
3.00k
    ImGuiContext& g = *GImGui;
9067
3.00k
    if (g.WheelingWindow != NULL)
9068
0
    {
9069
0
        g.WheelingWindowReleaseTimer -= g.IO.DeltaTime;
9070
0
        if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
9071
0
            g.WheelingWindowReleaseTimer = 0.0f;
9072
0
        if (g.WheelingWindowReleaseTimer <= 0.0f)
9073
0
            LockWheelingWindow(NULL, 0.0f);
9074
0
    }
9075
9076
3.00k
    ImVec2 wheel;
9077
3.00k
    wheel.x = TestKeyOwner(ImGuiKey_MouseWheelX, ImGuiKeyOwner_None) ? g.IO.MouseWheelH : 0.0f;
9078
3.00k
    wheel.y = TestKeyOwner(ImGuiKey_MouseWheelY, ImGuiKeyOwner_None) ? g.IO.MouseWheel : 0.0f;
9079
9080
    //IMGUI_DEBUG_LOG("MouseWheel X:%.3f Y:%.3f\n", wheel_x, wheel_y);
9081
3.00k
    ImGuiWindow* mouse_window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
9082
3.00k
    if (!mouse_window || mouse_window->Collapsed)
9083
3.00k
        return;
9084
9085
    // Zoom / Scale window
9086
    // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
9087
0
    if (wheel.y != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
9088
0
    {
9089
0
        LockWheelingWindow(mouse_window, wheel.y);
9090
0
        ImGuiWindow* window = mouse_window;
9091
0
        const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
9092
0
        const float scale = new_font_scale / window->FontWindowScale;
9093
0
        window->FontWindowScale = new_font_scale;
9094
0
        if (window == window->RootWindow)
9095
0
        {
9096
0
            const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
9097
0
            SetWindowPos(window, window->Pos + offset, 0);
9098
0
            window->Size = ImFloor(window->Size * scale);
9099
0
            window->SizeFull = ImFloor(window->SizeFull * scale);
9100
0
        }
9101
0
        return;
9102
0
    }
9103
0
    if (g.IO.KeyCtrl)
9104
0
        return;
9105
9106
    // Mouse wheel scrolling
9107
    // As a standard behavior holding SHIFT while using Vertical Mouse Wheel triggers Horizontal scroll instead
9108
    // - We avoid doing it on OSX as it the OS input layer handles this already.
9109
    // - However this means when running on OSX over Emcripten, Shift+WheelY will incur two swappings (1 in OS, 1 here), cancelling the feature.
9110
0
    const bool swap_axis = g.IO.KeyShift && !g.IO.ConfigMacOSXBehaviors;
9111
0
    if (swap_axis)
9112
0
    {
9113
0
        wheel.x = wheel.y;
9114
0
        wheel.y = 0.0f;
9115
0
    }
9116
9117
    // Maintain a rough average of moving magnitude on both axises
9118
    // FIXME: should by based on wall clock time rather than frame-counter
9119
0
    g.WheelingAxisAvg.x = ImExponentialMovingAverage(g.WheelingAxisAvg.x, ImAbs(wheel.x), 30);
9120
0
    g.WheelingAxisAvg.y = ImExponentialMovingAverage(g.WheelingAxisAvg.y, ImAbs(wheel.y), 30);
9121
9122
    // In the rare situation where FindBestWheelingWindow() had to defer first frame of wheeling due to ambiguous main axis, reinject it now.
9123
0
    wheel += g.WheelingWindowWheelRemainder;
9124
0
    g.WheelingWindowWheelRemainder = ImVec2(0.0f, 0.0f);
9125
0
    if (wheel.x == 0.0f && wheel.y == 0.0f)
9126
0
        return;
9127
9128
    // Mouse wheel scrolling: find target and apply
9129
    // - don't renew lock if axis doesn't apply on the window.
9130
    // - select a main axis when both axises are being moved.
9131
0
    if (ImGuiWindow* window = (g.WheelingWindow ? g.WheelingWindow : FindBestWheelingWindow(wheel)))
9132
0
        if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
9133
0
        {
9134
0
            bool do_scroll[2] = { wheel.x != 0.0f && window->ScrollMax.x != 0.0f, wheel.y != 0.0f && window->ScrollMax.y != 0.0f };
9135
0
            if (do_scroll[ImGuiAxis_X] && do_scroll[ImGuiAxis_Y])
9136
0
                do_scroll[(g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? ImGuiAxis_Y : ImGuiAxis_X] = false;
9137
0
            if (do_scroll[ImGuiAxis_X])
9138
0
            {
9139
0
                LockWheelingWindow(window, wheel.x);
9140
0
                float max_step = window->InnerRect.GetWidth() * 0.67f;
9141
0
                float scroll_step = ImFloor(ImMin(2 * window->CalcFontSize(), max_step));
9142
0
                SetScrollX(window, window->Scroll.x - wheel.x * scroll_step);
9143
0
            }
9144
0
            if (do_scroll[ImGuiAxis_Y])
9145
0
            {
9146
0
                LockWheelingWindow(window, wheel.y);
9147
0
                float max_step = window->InnerRect.GetHeight() * 0.67f;
9148
0
                float scroll_step = ImFloor(ImMin(5 * window->CalcFontSize(), max_step));
9149
0
                SetScrollY(window, window->Scroll.y - wheel.y * scroll_step);
9150
0
            }
9151
0
        }
9152
0
}
9153
9154
void ImGui::SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard)
9155
0
{
9156
0
    ImGuiContext& g = *GImGui;
9157
0
    g.WantCaptureKeyboardNextFrame = want_capture_keyboard ? 1 : 0;
9158
0
}
9159
9160
void ImGui::SetNextFrameWantCaptureMouse(bool want_capture_mouse)
9161
0
{
9162
0
    ImGuiContext& g = *GImGui;
9163
0
    g.WantCaptureMouseNextFrame = want_capture_mouse ? 1 : 0;
9164
0
}
9165
9166
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9167
static const char* GetInputSourceName(ImGuiInputSource source)
9168
0
{
9169
0
    const char* input_source_names[] = { "None", "Mouse", "Keyboard", "Gamepad", "Nav", "Clipboard" };
9170
0
    IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT && source >= 0 && source < ImGuiInputSource_COUNT);
9171
0
    return input_source_names[source];
9172
0
}
9173
static void DebugPrintInputEvent(const char* prefix, const ImGuiInputEvent* e)
9174
0
{
9175
0
    ImGuiContext& g = *GImGui;
9176
0
    if (e->Type == ImGuiInputEventType_MousePos)    { if (e->MousePos.PosX == -FLT_MAX && e->MousePos.PosY == -FLT_MAX) IMGUI_DEBUG_LOG_IO("%s: MousePos (-FLT_MAX, -FLT_MAX)\n", prefix); else IMGUI_DEBUG_LOG_IO("%s: MousePos (%.1f, %.1f)\n", prefix, e->MousePos.PosX, e->MousePos.PosY); return; }
9177
0
    if (e->Type == ImGuiInputEventType_MouseButton) { IMGUI_DEBUG_LOG_IO("%s: MouseButton %d %s\n", prefix, e->MouseButton.Button, e->MouseButton.Down ? "Down" : "Up"); return; }
9178
0
    if (e->Type == ImGuiInputEventType_MouseWheel)  { IMGUI_DEBUG_LOG_IO("%s: MouseWheel (%.3f, %.3f)\n", prefix, e->MouseWheel.WheelX, e->MouseWheel.WheelY); return; }
9179
0
    if (e->Type == ImGuiInputEventType_MouseViewport){IMGUI_DEBUG_LOG_IO("%s: MouseViewport (0x%08X)\n", prefix, e->MouseViewport.HoveredViewportID); return; }
9180
0
    if (e->Type == ImGuiInputEventType_Key)         { IMGUI_DEBUG_LOG_IO("%s: Key \"%s\" %s\n", prefix, ImGui::GetKeyName(e->Key.Key), e->Key.Down ? "Down" : "Up"); return; }
9181
0
    if (e->Type == ImGuiInputEventType_Text)        { IMGUI_DEBUG_LOG_IO("%s: Text: %c (U+%08X)\n", prefix, e->Text.Char, e->Text.Char); return; }
9182
0
    if (e->Type == ImGuiInputEventType_Focus)       { IMGUI_DEBUG_LOG_IO("%s: AppFocused %d\n", prefix, e->AppFocused.Focused); return; }
9183
0
}
9184
#endif
9185
9186
// Process input queue
9187
// We always call this with the value of 'bool g.IO.ConfigInputTrickleEventQueue'.
9188
// - trickle_fast_inputs = false : process all events, turn into flattened input state (e.g. successive down/up/down/up will be lost)
9189
// - trickle_fast_inputs = true  : process as many events as possible (successive down/up/down/up will be trickled over several frames so nothing is lost) (new feature in 1.87)
9190
void ImGui::UpdateInputEvents(bool trickle_fast_inputs)
9191
3.00k
{
9192
3.00k
    ImGuiContext& g = *GImGui;
9193
3.00k
    ImGuiIO& io = g.IO;
9194
9195
    // Only trickle chars<>key when working with InputText()
9196
    // FIXME: InputText() could parse event trail?
9197
    // FIXME: Could specialize chars<>keys trickling rules for control keys (those not typically associated to characters)
9198
3.00k
    const bool trickle_interleaved_keys_and_text = (trickle_fast_inputs && g.WantTextInputNextFrame == 1);
9199
9200
3.00k
    bool mouse_moved = false, mouse_wheeled = false, key_changed = false, text_inputted = false;
9201
3.00k
    int  mouse_button_changed = 0x00;
9202
3.00k
    ImBitArray<ImGuiKey_KeysData_SIZE> key_changed_mask;
9203
9204
3.00k
    int event_n = 0;
9205
4.42k
    for (; event_n < g.InputEventsQueue.Size; event_n++)
9206
2.01k
    {
9207
2.01k
        ImGuiInputEvent* e = &g.InputEventsQueue[event_n];
9208
2.01k
        if (e->Type == ImGuiInputEventType_MousePos)
9209
251
        {
9210
            // Trickling Rule: Stop processing queued events if we already handled a mouse button change
9211
251
            ImVec2 event_pos(e->MousePos.PosX, e->MousePos.PosY);
9212
251
            if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_wheeled || key_changed || text_inputted))
9213
46
                break;
9214
205
            io.MousePos = event_pos;
9215
205
            mouse_moved = true;
9216
205
        }
9217
1.76k
        else if (e->Type == ImGuiInputEventType_MouseButton)
9218
1.12k
        {
9219
            // Trickling Rule: Stop processing queued events if we got multiple action on the same button
9220
1.12k
            const ImGuiMouseButton button = e->MouseButton.Button;
9221
1.12k
            IM_ASSERT(button >= 0 && button < ImGuiMouseButton_COUNT);
9222
1.12k
            if (trickle_fast_inputs && ((mouse_button_changed & (1 << button)) || mouse_wheeled))
9223
459
                break;
9224
663
            io.MouseDown[button] = e->MouseButton.Down;
9225
663
            mouse_button_changed |= (1 << button);
9226
663
        }
9227
641
        else if (e->Type == ImGuiInputEventType_MouseWheel)
9228
161
        {
9229
            // Trickling Rule: Stop processing queued events if we got multiple action on the event
9230
161
            if (trickle_fast_inputs && (mouse_moved || mouse_button_changed != 0))
9231
40
                break;
9232
121
            io.MouseWheelH += e->MouseWheel.WheelX;
9233
121
            io.MouseWheel += e->MouseWheel.WheelY;
9234
121
            mouse_wheeled = true;
9235
121
        }
9236
480
        else if (e->Type == ImGuiInputEventType_MouseViewport)
9237
0
        {
9238
0
            io.MouseHoveredViewport = e->MouseViewport.HoveredViewportID;
9239
0
        }
9240
480
        else if (e->Type == ImGuiInputEventType_Key)
9241
47
        {
9242
            // Trickling Rule: Stop processing queued events if we got multiple action on the same button
9243
47
            ImGuiKey key = e->Key.Key;
9244
47
            IM_ASSERT(key != ImGuiKey_None);
9245
47
            ImGuiKeyData* key_data = GetKeyData(key);
9246
47
            const int key_data_index = (int)(key_data - g.IO.KeysData);
9247
47
            if (trickle_fast_inputs && key_data->Down != e->Key.Down && (key_changed_mask.TestBit(key_data_index) || text_inputted || mouse_button_changed != 0))
9248
6
                break;
9249
41
            key_data->Down = e->Key.Down;
9250
41
            key_data->AnalogValue = e->Key.AnalogValue;
9251
41
            key_changed = true;
9252
41
            key_changed_mask.SetBit(key_data_index);
9253
9254
            // Allow legacy code using io.KeysDown[GetKeyIndex()] with new backends
9255
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9256
            io.KeysDown[key_data_index] = key_data->Down;
9257
            if (io.KeyMap[key_data_index] != -1)
9258
                io.KeysDown[io.KeyMap[key_data_index]] = key_data->Down;
9259
#endif
9260
41
        }
9261
433
        else if (e->Type == ImGuiInputEventType_Text)
9262
369
        {
9263
            // Trickling Rule: Stop processing queued events if keys/mouse have been interacted with
9264
369
            if (trickle_fast_inputs && ((key_changed && trickle_interleaved_keys_and_text) || mouse_button_changed != 0 || mouse_moved || mouse_wheeled))
9265
37
                break;
9266
332
            unsigned int c = e->Text.Char;
9267
332
            io.InputQueueCharacters.push_back(c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID);
9268
332
            if (trickle_interleaved_keys_and_text)
9269
0
                text_inputted = true;
9270
332
        }
9271
64
        else if (e->Type == ImGuiInputEventType_Focus)
9272
64
        {
9273
            // We intentionally overwrite this and process in NewFrame(), in order to give a chance
9274
            // to multi-viewports backends to queue AddFocusEvent(false) + AddFocusEvent(true) in same frame.
9275
64
            const bool focus_lost = !e->AppFocused.Focused;
9276
64
            io.AppFocusLost = focus_lost;
9277
64
        }
9278
0
        else
9279
0
        {
9280
0
            IM_ASSERT(0 && "Unknown event!");
9281
0
        }
9282
2.01k
    }
9283
9284
    // Record trail (for domain-specific applications wanting to access a precise trail)
9285
    //if (event_n != 0) IMGUI_DEBUG_LOG_IO("Processed: %d / Remaining: %d\n", event_n, g.InputEventsQueue.Size - event_n);
9286
4.42k
    for (int n = 0; n < event_n; n++)
9287
1.42k
        g.InputEventsTrail.push_back(g.InputEventsQueue[n]);
9288
9289
    // [DEBUG]
9290
3.00k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9291
3.00k
    if (event_n != 0 && (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO))
9292
0
        for (int n = 0; n < g.InputEventsQueue.Size; n++)
9293
0
            DebugPrintInputEvent(n < event_n ? "Processed" : "Remaining", &g.InputEventsQueue[n]);
9294
3.00k
#endif
9295
9296
    // Remaining events will be processed on the next frame
9297
3.00k
    if (event_n == g.InputEventsQueue.Size)
9298
2.41k
        g.InputEventsQueue.resize(0);
9299
588
    else
9300
588
        g.InputEventsQueue.erase(g.InputEventsQueue.Data, g.InputEventsQueue.Data + event_n);
9301
9302
    // Clear buttons state when focus is lost
9303
    // - this is useful so e.g. releasing Alt after focus loss on Alt-Tab doesn't trigger the Alt menu toggle.
9304
    // - we clear in EndFrame() and not now in order allow application/user code polling this flag
9305
    //   (e.g. custom backend may want to clear additional data, custom widgets may want to react with a "canceling" event).
9306
3.00k
    if (g.IO.AppFocusLost)
9307
64
        g.IO.ClearInputKeys();
9308
3.00k
}
9309
9310
ImGuiID ImGui::GetKeyOwner(ImGuiKey key)
9311
0
{
9312
0
    if (!IsNamedKeyOrModKey(key))
9313
0
        return ImGuiKeyOwner_None;
9314
9315
0
    ImGuiContext& g = *GImGui;
9316
0
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(key);
9317
0
    ImGuiID owner_id = owner_data->OwnerCurr;
9318
9319
0
    if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
9320
0
        if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
9321
0
            return ImGuiKeyOwner_None;
9322
9323
0
    return owner_id;
9324
0
}
9325
9326
// TestKeyOwner(..., ID)   : (owner == None || owner == ID)
9327
// TestKeyOwner(..., None) : (owner == None)
9328
// TestKeyOwner(..., Any)  : no owner test
9329
// All paths are also testing for key not being locked, for the rare cases that key have been locked with using ImGuiInputFlags_LockXXX flags.
9330
bool ImGui::TestKeyOwner(ImGuiKey key, ImGuiID owner_id)
9331
6.61k
{
9332
6.61k
    if (!IsNamedKeyOrModKey(key))
9333
0
        return true;
9334
9335
6.61k
    ImGuiContext& g = *GImGui;
9336
6.61k
    if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
9337
0
        if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
9338
0
            return false;
9339
9340
6.61k
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(key);
9341
6.61k
    if (owner_id == ImGuiKeyOwner_Any)
9342
352
        return (owner_data->LockThisFrame == false);
9343
9344
    // Note: SetKeyOwner() sets OwnerCurr. It is not strictly required for most mouse routing overlap (because of ActiveId/HoveredId
9345
    // are acting as filter before this has a chance to filter), but sane as soon as user tries to look into things.
9346
    // Setting OwnerCurr in SetKeyOwner() is more consistent than testing OwnerNext here: would be inconsistent with getter and other functions.
9347
6.25k
    if (owner_data->OwnerCurr != owner_id)
9348
0
    {
9349
0
        if (owner_data->LockThisFrame)
9350
0
            return false;
9351
0
        if (owner_data->OwnerCurr != ImGuiKeyOwner_None)
9352
0
            return false;
9353
0
    }
9354
9355
6.25k
    return true;
9356
6.25k
}
9357
9358
// _LockXXX flags are useful to lock keys away from code which is not input-owner aware.
9359
// When using _LockXXX flags, you can use ImGuiKeyOwner_Any to lock keys from everyone.
9360
// - SetKeyOwner(..., None)              : clears owner
9361
// - SetKeyOwner(..., Any, !Lock)        : illegal (assert)
9362
// - SetKeyOwner(..., Any or None, Lock) : set lock
9363
void ImGui::SetKeyOwner(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
9364
0
{
9365
0
    IM_ASSERT(IsNamedKeyOrModKey(key) && (owner_id != ImGuiKeyOwner_Any || (flags & (ImGuiInputFlags_LockThisFrame | ImGuiInputFlags_LockUntilRelease)))); // Can only use _Any with _LockXXX flags (to eat a key away without an ID to retrieve it)
9366
0
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetKeyOwner) == 0); // Passing flags not supported by this function!
9367
9368
0
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(key);
9369
0
    owner_data->OwnerCurr = owner_data->OwnerNext = owner_id;
9370
9371
    // We cannot lock by default as it would likely break lots of legacy code.
9372
    // In the case of using LockUntilRelease while key is not down we still lock during the frame (no key_data->Down test)
9373
0
    owner_data->LockUntilRelease = (flags & ImGuiInputFlags_LockUntilRelease) != 0;
9374
0
    owner_data->LockThisFrame = (flags & ImGuiInputFlags_LockThisFrame) != 0 || (owner_data->LockUntilRelease);
9375
0
}
9376
9377
// This is more or less equivalent to:
9378
//   if (IsItemHovered() || IsItemActive())
9379
//       SetKeyOwner(key, GetItemID());
9380
// Extensive uses of that (e.g. many calls for a single item) may want to manually perform the tests once and then call SetKeyOwner() multiple times.
9381
// More advanced usage scenarios may want to call SetKeyOwner() manually based on different condition.
9382
// Worth noting is that only one item can be hovered and only one item can be active, therefore this usage pattern doesn't need to bother with routing and priority.
9383
void ImGui::SetItemKeyOwner(ImGuiKey key, ImGuiInputFlags flags)
9384
0
{
9385
0
    ImGuiContext& g = *GImGui;
9386
0
    ImGuiID id = g.LastItemData.ID;
9387
0
    if (id == 0 || (g.HoveredId != id && g.ActiveId != id))
9388
0
        return;
9389
0
    if ((flags & ImGuiInputFlags_CondMask_) == 0)
9390
0
        flags |= ImGuiInputFlags_CondDefault_;
9391
0
    if ((g.HoveredId == id && (flags & ImGuiInputFlags_CondHovered)) || (g.ActiveId == id && (flags & ImGuiInputFlags_CondActive)))
9392
0
    {
9393
0
        IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetItemKeyOwner) == 0); // Passing flags not supported by this function!
9394
0
        SetKeyOwner(key, id, flags & ~ImGuiInputFlags_CondMask_);
9395
0
    }
9396
0
}
9397
9398
bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
9399
6.00k
{
9400
6.00k
    ImGuiContext& g = *GImGui;
9401
9402
    // When using (owner_id == 0/Any): SetShortcutRouting() will use CurrentFocusScopeId and filter with this, so IsKeyPressed() is fine with he 0/Any.
9403
6.00k
    if ((flags & ImGuiInputFlags_RouteMask_) == 0)
9404
6.00k
        flags |= ImGuiInputFlags_RouteFocused;
9405
6.00k
    if (!SetShortcutRouting(key_chord, owner_id, flags))
9406
0
        return false;
9407
9408
6.00k
    if (key_chord & ImGuiMod_Shortcut)
9409
0
        key_chord = ConvertShortcutMod(key_chord);
9410
6.00k
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
9411
6.00k
    if (g.IO.KeyMods != mods)
9412
6.00k
        return false;
9413
9414
    // Special storage location for mods
9415
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9416
0
    if (key == ImGuiKey_None)
9417
0
        key = ConvertSingleModFlagToKey(mods);
9418
9419
0
    if (!IsKeyPressed(key, owner_id, (flags & (ImGuiInputFlags_Repeat | (ImGuiInputFlags)ImGuiInputFlags_RepeatRateMask_))))
9420
0
        return false;
9421
0
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByShortcut) == 0); // Passing flags not supported by this function!
9422
9423
0
    return true;
9424
0
}
9425
9426
9427
//-----------------------------------------------------------------------------
9428
// [SECTION] ERROR CHECKING
9429
//-----------------------------------------------------------------------------
9430
9431
// Helper function to verify ABI compatibility between caller code and compiled version of Dear ImGui.
9432
// Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
9433
// If this triggers you have an issue:
9434
// - Most commonly: mismatched headers and compiled code version.
9435
// - Or: mismatched configuration #define, compilation settings, packing pragma etc.
9436
//   The configuration settings mentioned in imconfig.h must be set for all compilation units involved with Dear ImGui,
9437
//   which is way it is required you put them in your imconfig file (and not just before including imgui.h).
9438
//   Otherwise it is possible that different compilation units would see different structure layout
9439
bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx)
9440
1
{
9441
1
    bool error = false;
9442
1
    if (strcmp(version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); }
9443
1
    if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
9444
1
    if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
9445
1
    if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
9446
1
    if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
9447
1
    if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
9448
1
    if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
9449
1
    return !error;
9450
1
}
9451
9452
// Until 1.89 (IMGUI_VERSION_NUM < 18814) it was legal to use SetCursorPos() to extend the boundary of a parent (e.g. window or table cell)
9453
// This is causing issues and ambiguity and we need to retire that.
9454
// See https://github.com/ocornut/imgui/issues/5548 for more details.
9455
// [Scenario 1]
9456
//  Previously this would make the window content size ~200x200:
9457
//    Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();  // NOT OK
9458
//  Instead, please submit an item:
9459
//    Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); // OK
9460
//  Alternative:
9461
//    Begin(...) + Dummy(ImVec2(200,200)) + End(); // OK
9462
// [Scenario 2]
9463
//  For reference this is one of the issue what we aim to fix with this change:
9464
//    BeginGroup() + SomeItem("foobar") + SetCursorScreenPos(GetCursorScreenPos()) + EndGroup()
9465
//  The previous logic made SetCursorScreenPos(GetCursorScreenPos()) have a side-effect! It would erroneously incorporate ItemSpacing.y after the item into content size, making the group taller!
9466
//  While this code is a little twisted, no-one would expect SetXXX(GetXXX()) to have a side-effect. Using vertical alignment patterns could trigger this issue.
9467
void ImGui::ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
9468
0
{
9469
0
    ImGuiContext& g = *GImGui;
9470
0
    ImGuiWindow* window = g.CurrentWindow;
9471
0
    IM_ASSERT(window->DC.IsSetPos);
9472
0
    window->DC.IsSetPos = false;
9473
0
#ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
9474
0
    if (window->DC.CursorPos.x <= window->DC.CursorMaxPos.x && window->DC.CursorPos.y <= window->DC.CursorMaxPos.y)
9475
0
        return;
9476
0
    if (window->SkipItems)
9477
0
        return;
9478
0
    IM_ASSERT(0 && "Code uses SetCursorPos()/SetCursorScreenPos() to extend window/parent boundaries. Please submit an item e.g. Dummy() to validate extent.");
9479
#else
9480
    window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
9481
#endif
9482
0
}
9483
9484
static void ImGui::ErrorCheckNewFrameSanityChecks()
9485
3.00k
{
9486
3.00k
    ImGuiContext& g = *GImGui;
9487
9488
    // Check user IM_ASSERT macro
9489
    // (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means your assert macro is incorrectly defined!
9490
    //  If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block.
9491
    //  This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.)
9492
    // #define IM_ASSERT(EXPR)   if (SomeCode(EXPR)) SomeMoreCode();                    // Wrong!
9493
    // #define IM_ASSERT(EXPR)   do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0)   // Correct!
9494
3.00k
    if (true) IM_ASSERT(1); else IM_ASSERT(0);
9495
9496
    // Emscripten backends are often imprecise in their submission of DeltaTime. (#6114, #3644)
9497
    // Ideally the Emscripten app/backend should aim to fix or smooth this value and avoid feeding zero, but we tolerate it.
9498
#ifdef __EMSCRIPTEN__
9499
    if (g.IO.DeltaTime <= 0.0f && g.FrameCount > 0)
9500
        g.IO.DeltaTime = 0.00001f;
9501
#endif
9502
9503
    // Check user data
9504
    // (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument)
9505
3.00k
    IM_ASSERT(g.Initialized);
9506
3.00k
    IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0)              && "Need a positive DeltaTime!");
9507
3.00k
    IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount)  && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
9508
3.00k
    IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f  && "Invalid DisplaySize value!");
9509
3.00k
    IM_ASSERT(g.IO.Fonts->IsBuilt()                                     && "Font Atlas not built! Make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()");
9510
3.00k
    IM_ASSERT(g.Style.CurveTessellationTol > 0.0f                       && "Invalid style setting!");
9511
3.00k
    IM_ASSERT(g.Style.CircleTessellationMaxError > 0.0f                 && "Invalid style setting!");
9512
3.00k
    IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f            && "Invalid style setting!"); // Allows us to avoid a few clamps in color computations
9513
3.00k
    IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting.");
9514
3.00k
    IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
9515
3.00k
    IM_ASSERT(g.Style.ColorButtonPosition == ImGuiDir_Left || g.Style.ColorButtonPosition == ImGuiDir_Right);
9516
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9517
    for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_COUNT; n++)
9518
        IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < ImGuiKey_LegacyNativeKey_END && "io.KeyMap[] contains an out of bound value (need to be 0..511, or -1 for unmapped key)");
9519
9520
    // Check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only added in 1.60 WIP)
9521
    if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && g.IO.BackendUsingLegacyKeyArrays == 1)
9522
        IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
9523
#endif
9524
9525
    // Check: the io.ConfigWindowsResizeFromEdges option requires backend to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly.
9526
3.00k
    if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors))
9527
1
        g.IO.ConfigWindowsResizeFromEdges = false;
9528
9529
    // Perform simple check: error if Docking or Viewport are enabled _exactly_ on frame 1 (instead of frame 0 or later), which is a common error leading to loss of .ini data.
9530
3.00k
    if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_DockingEnable) == 0)
9531
3.00k
        IM_ASSERT(0 && "Please set DockingEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
9532
3.00k
    if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable) == 0)
9533
3.00k
        IM_ASSERT(0 && "Please set ViewportsEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
9534
9535
    // Perform simple checks: multi-viewport and platform windows support
9536
3.00k
    if (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
9537
1
    {
9538
1
        if ((g.IO.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasViewports))
9539
0
        {
9540
0
            IM_ASSERT((g.FrameCount == 0 || g.FrameCount == g.FrameCountPlatformEnded) && "Forgot to call UpdatePlatformWindows() in main loop after EndFrame()? Check examples/ applications for reference.");
9541
0
            IM_ASSERT(g.PlatformIO.Platform_CreateWindow  != NULL && "Platform init didn't install handlers?");
9542
0
            IM_ASSERT(g.PlatformIO.Platform_DestroyWindow != NULL && "Platform init didn't install handlers?");
9543
0
            IM_ASSERT(g.PlatformIO.Platform_GetWindowPos  != NULL && "Platform init didn't install handlers?");
9544
0
            IM_ASSERT(g.PlatformIO.Platform_SetWindowPos  != NULL && "Platform init didn't install handlers?");
9545
0
            IM_ASSERT(g.PlatformIO.Platform_GetWindowSize != NULL && "Platform init didn't install handlers?");
9546
0
            IM_ASSERT(g.PlatformIO.Platform_SetWindowSize != NULL && "Platform init didn't install handlers?");
9547
0
            IM_ASSERT(g.PlatformIO.Monitors.Size > 0 && "Platform init didn't setup Monitors list?");
9548
0
            IM_ASSERT((g.Viewports[0]->PlatformUserData != NULL || g.Viewports[0]->PlatformHandle != NULL) && "Platform init didn't setup main viewport.");
9549
0
            if (g.IO.ConfigDockingTransparentPayload && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
9550
0
                IM_ASSERT(g.PlatformIO.Platform_SetWindowAlpha != NULL && "Platform_SetWindowAlpha handler is required to use io.ConfigDockingTransparent!");
9551
0
        }
9552
1
        else
9553
1
        {
9554
            // Disable feature, our backends do not support it
9555
1
            g.IO.ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable;
9556
1
        }
9557
9558
        // Perform simple checks on platform monitor data + compute a total bounding box for quick early outs
9559
1
        for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
9560
0
        {
9561
0
            ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[monitor_n];
9562
0
            IM_UNUSED(mon);
9563
0
            IM_ASSERT(mon.MainSize.x > 0.0f && mon.MainSize.y > 0.0f && "Monitor main bounds not setup properly.");
9564
0
            IM_ASSERT(ImRect(mon.MainPos, mon.MainPos + mon.MainSize).Contains(ImRect(mon.WorkPos, mon.WorkPos + mon.WorkSize)) && "Monitor work bounds not setup properly. If you don't have work area information, just copy MainPos/MainSize into them.");
9565
0
            IM_ASSERT(mon.DpiScale != 0.0f);
9566
0
        }
9567
1
    }
9568
3.00k
}
9569
9570
static void ImGui::ErrorCheckEndFrameSanityChecks()
9571
3.00k
{
9572
3.00k
    ImGuiContext& g = *GImGui;
9573
9574
    // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame()
9575
    // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame().
9576
    // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will
9577
    // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs.
9578
    // We silently accommodate for this case by ignoring the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0),
9579
    // while still correctly asserting on mid-frame key press events.
9580
3.00k
    const ImGuiKeyChord key_mods = GetMergedModsFromKeys();
9581
3.00k
    IM_ASSERT((key_mods == 0 || g.IO.KeyMods == key_mods) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods");
9582
3.00k
    IM_UNUSED(key_mods);
9583
9584
    // [EXPERIMENTAL] Recover from errors: You may call this yourself before EndFrame().
9585
    //ErrorCheckEndFrameRecover();
9586
9587
    // Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
9588
    // to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
9589
3.00k
    if (g.CurrentWindowStack.Size != 1)
9590
0
    {
9591
0
        if (g.CurrentWindowStack.Size > 1)
9592
0
        {
9593
0
            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
9594
0
            while (g.CurrentWindowStack.Size > 1)
9595
0
                End();
9596
0
        }
9597
0
        else
9598
0
        {
9599
0
            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
9600
0
        }
9601
0
    }
9602
9603
3.00k
    IM_ASSERT_USER_ERROR(g.GroupStack.Size == 0, "Missing EndGroup call!");
9604
3.00k
}
9605
9606
// Experimental recovery from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.
9607
// Must be called during or before EndFrame().
9608
// This is generally flawed as we are not necessarily End/Popping things in the right order.
9609
// FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
9610
// FIXME: Can't recover from interleaved BeginTabBar/Begin
9611
void    ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data)
9612
0
{
9613
    // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations"
9614
0
    ImGuiContext& g = *GImGui;
9615
0
    while (g.CurrentWindowStack.Size > 0) //-V1044
9616
0
    {
9617
0
        ErrorCheckEndWindowRecover(log_callback, user_data);
9618
0
        ImGuiWindow* window = g.CurrentWindow;
9619
0
        if (g.CurrentWindowStack.Size == 1)
9620
0
        {
9621
0
            IM_ASSERT(window->IsFallbackWindow);
9622
0
            break;
9623
0
        }
9624
0
        if (window->Flags & ImGuiWindowFlags_ChildWindow)
9625
0
        {
9626
0
            if (log_callback) log_callback(user_data, "Recovered from missing EndChild() for '%s'", window->Name);
9627
0
            EndChild();
9628
0
        }
9629
0
        else
9630
0
        {
9631
0
            if (log_callback) log_callback(user_data, "Recovered from missing End() for '%s'", window->Name);
9632
0
            End();
9633
0
        }
9634
0
    }
9635
0
}
9636
9637
// Must be called before End()/EndChild()
9638
void    ImGui::ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, void* user_data)
9639
0
{
9640
0
    ImGuiContext& g = *GImGui;
9641
0
    while (g.CurrentTable && (g.CurrentTable->OuterWindow == g.CurrentWindow || g.CurrentTable->InnerWindow == g.CurrentWindow))
9642
0
    {
9643
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndTable() in '%s'", g.CurrentTable->OuterWindow->Name);
9644
0
        EndTable();
9645
0
    }
9646
9647
0
    ImGuiWindow* window = g.CurrentWindow;
9648
0
    ImGuiStackSizes* stack_sizes = &g.CurrentWindowStack.back().StackSizesOnBegin;
9649
0
    IM_ASSERT(window != NULL);
9650
0
    while (g.CurrentTabBar != NULL) //-V1044
9651
0
    {
9652
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndTabBar() in '%s'", window->Name);
9653
0
        EndTabBar();
9654
0
    }
9655
0
    while (window->DC.TreeDepth > 0)
9656
0
    {
9657
0
        if (log_callback) log_callback(user_data, "Recovered from missing TreePop() in '%s'", window->Name);
9658
0
        TreePop();
9659
0
    }
9660
0
    while (g.GroupStack.Size > stack_sizes->SizeOfGroupStack) //-V1044
9661
0
    {
9662
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndGroup() in '%s'", window->Name);
9663
0
        EndGroup();
9664
0
    }
9665
0
    while (window->IDStack.Size > 1)
9666
0
    {
9667
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopID() in '%s'", window->Name);
9668
0
        PopID();
9669
0
    }
9670
0
    while (g.DisabledStackSize > stack_sizes->SizeOfDisabledStack) //-V1044
9671
0
    {
9672
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndDisabled() in '%s'", window->Name);
9673
0
        EndDisabled();
9674
0
    }
9675
0
    while (g.ColorStack.Size > stack_sizes->SizeOfColorStack)
9676
0
    {
9677
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleColor() in '%s' for ImGuiCol_%s", window->Name, GetStyleColorName(g.ColorStack.back().Col));
9678
0
        PopStyleColor();
9679
0
    }
9680
0
    while (g.ItemFlagsStack.Size > stack_sizes->SizeOfItemFlagsStack) //-V1044
9681
0
    {
9682
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopItemFlag() in '%s'", window->Name);
9683
0
        PopItemFlag();
9684
0
    }
9685
0
    while (g.StyleVarStack.Size > stack_sizes->SizeOfStyleVarStack) //-V1044
9686
0
    {
9687
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleVar() in '%s'", window->Name);
9688
0
        PopStyleVar();
9689
0
    }
9690
0
    while (g.FocusScopeStack.Size > stack_sizes->SizeOfFocusScopeStack + 1) //-V1044
9691
0
    {
9692
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopFocusScope() in '%s'", window->Name);
9693
0
        PopFocusScope();
9694
0
    }
9695
0
}
9696
9697
// Save current stack sizes for later compare
9698
void ImGuiStackSizes::SetToCurrentState()
9699
9.00k
{
9700
9.00k
    ImGuiContext& g = *GImGui;
9701
9.00k
    ImGuiWindow* window = g.CurrentWindow;
9702
9.00k
    SizeOfIDStack = (short)window->IDStack.Size;
9703
9.00k
    SizeOfColorStack = (short)g.ColorStack.Size;
9704
9.00k
    SizeOfStyleVarStack = (short)g.StyleVarStack.Size;
9705
9.00k
    SizeOfFontStack = (short)g.FontStack.Size;
9706
9.00k
    SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size;
9707
9.00k
    SizeOfGroupStack = (short)g.GroupStack.Size;
9708
9.00k
    SizeOfItemFlagsStack = (short)g.ItemFlagsStack.Size;
9709
9.00k
    SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size;
9710
9.00k
    SizeOfDisabledStack = (short)g.DisabledStackSize;
9711
9.00k
}
9712
9713
// Compare to detect usage errors
9714
void ImGuiStackSizes::CompareWithCurrentState()
9715
9.00k
{
9716
9.00k
    ImGuiContext& g = *GImGui;
9717
9.00k
    ImGuiWindow* window = g.CurrentWindow;
9718
9.00k
    IM_UNUSED(window);
9719
9720
    // Window stacks
9721
    // NOT checking: DC.ItemWidth, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
9722
9.00k
    IM_ASSERT(SizeOfIDStack         == window->IDStack.Size     && "PushID/PopID or TreeNode/TreePop Mismatch!");
9723
9724
    // Global stacks
9725
    // For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them.
9726
9.00k
    IM_ASSERT(SizeOfGroupStack      == g.GroupStack.Size        && "BeginGroup/EndGroup Mismatch!");
9727
9.00k
    IM_ASSERT(SizeOfBeginPopupStack == g.BeginPopupStack.Size   && "BeginPopup/EndPopup or BeginMenu/EndMenu Mismatch!");
9728
9.00k
    IM_ASSERT(SizeOfDisabledStack   == g.DisabledStackSize      && "BeginDisabled/EndDisabled Mismatch!");
9729
9.00k
    IM_ASSERT(SizeOfItemFlagsStack  >= g.ItemFlagsStack.Size    && "PushItemFlag/PopItemFlag Mismatch!");
9730
9.00k
    IM_ASSERT(SizeOfColorStack      >= g.ColorStack.Size        && "PushStyleColor/PopStyleColor Mismatch!");
9731
9.00k
    IM_ASSERT(SizeOfStyleVarStack   >= g.StyleVarStack.Size     && "PushStyleVar/PopStyleVar Mismatch!");
9732
9.00k
    IM_ASSERT(SizeOfFontStack       >= g.FontStack.Size         && "PushFont/PopFont Mismatch!");
9733
9.00k
    IM_ASSERT(SizeOfFocusScopeStack == g.FocusScopeStack.Size   && "PushFocusScope/PopFocusScope Mismatch!");
9734
9.00k
}
9735
9736
9737
//-----------------------------------------------------------------------------
9738
// [SECTION] LAYOUT
9739
//-----------------------------------------------------------------------------
9740
// - ItemSize()
9741
// - ItemAdd()
9742
// - SameLine()
9743
// - GetCursorScreenPos()
9744
// - SetCursorScreenPos()
9745
// - GetCursorPos(), GetCursorPosX(), GetCursorPosY()
9746
// - SetCursorPos(), SetCursorPosX(), SetCursorPosY()
9747
// - GetCursorStartPos()
9748
// - Indent()
9749
// - Unindent()
9750
// - SetNextItemWidth()
9751
// - PushItemWidth()
9752
// - PushMultiItemsWidths()
9753
// - PopItemWidth()
9754
// - CalcItemWidth()
9755
// - CalcItemSize()
9756
// - GetTextLineHeight()
9757
// - GetTextLineHeightWithSpacing()
9758
// - GetFrameHeight()
9759
// - GetFrameHeightWithSpacing()
9760
// - GetContentRegionMax()
9761
// - GetContentRegionMaxAbs() [Internal]
9762
// - GetContentRegionAvail(),
9763
// - GetWindowContentRegionMin(), GetWindowContentRegionMax()
9764
// - BeginGroup()
9765
// - EndGroup()
9766
// Also see in imgui_widgets: tab bars, and in imgui_tables: tables, columns.
9767
//-----------------------------------------------------------------------------
9768
9769
// Advance cursor given item size for layout.
9770
// Register minimum needed size so it can extend the bounding box used for auto-fit calculation.
9771
// See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different.
9772
void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
9773
6.00k
{
9774
6.00k
    ImGuiContext& g = *GImGui;
9775
6.00k
    ImGuiWindow* window = g.CurrentWindow;
9776
6.00k
    if (window->SkipItems)
9777
0
        return;
9778
9779
    // We increase the height in this function to accommodate for baseline offset.
9780
    // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
9781
    // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
9782
6.00k
    const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
9783
9784
6.00k
    const float line_y1 = window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y;
9785
6.00k
    const float line_height = ImMax(window->DC.CurrLineSize.y, /*ImMax(*/window->DC.CursorPos.y - line_y1/*, 0.0f)*/ + size.y + offset_to_match_baseline_y);
9786
9787
    // Always align ourselves on pixel boundaries
9788
    //if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG]
9789
6.00k
    window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
9790
6.00k
    window->DC.CursorPosPrevLine.y = line_y1;
9791
6.00k
    window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);    // Next line
9792
6.00k
    window->DC.CursorPos.y = IM_FLOOR(line_y1 + line_height + g.Style.ItemSpacing.y);                       // Next line
9793
6.00k
    window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
9794
6.00k
    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
9795
    //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
9796
9797
6.00k
    window->DC.PrevLineSize.y = line_height;
9798
6.00k
    window->DC.CurrLineSize.y = 0.0f;
9799
6.00k
    window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y);
9800
6.00k
    window->DC.CurrLineTextBaseOffset = 0.0f;
9801
6.00k
    window->DC.IsSameLine = window->DC.IsSetPos = false;
9802
9803
    // Horizontal layout mode
9804
6.00k
    if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
9805
0
        SameLine();
9806
6.00k
}
9807
9808
// Declare item bounding box for clipping and interaction.
9809
// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
9810
// declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction.
9811
bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGuiItemFlags extra_flags)
9812
18.3k
{
9813
18.3k
    ImGuiContext& g = *GImGui;
9814
18.3k
    ImGuiWindow* window = g.CurrentWindow;
9815
9816
    // Set item data
9817
    // (DisplayRect is left untouched, made valid when ImGuiItemStatusFlags_HasDisplayRect is set)
9818
18.3k
    g.LastItemData.ID = id;
9819
18.3k
    g.LastItemData.Rect = bb;
9820
18.3k
    g.LastItemData.NavRect = nav_bb_arg ? *nav_bb_arg : bb;
9821
18.3k
    g.LastItemData.InFlags = g.CurrentItemFlags | extra_flags;
9822
18.3k
    g.LastItemData.StatusFlags = ImGuiItemStatusFlags_None;
9823
9824
    // Directional navigation processing
9825
18.3k
    if (id != 0)
9826
15.2k
    {
9827
15.2k
        KeepAliveID(id);
9828
9829
        // Runs prior to clipping early-out
9830
        //  (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
9831
        //  (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
9832
        //      unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
9833
        //      thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
9834
        //      We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
9835
        //      to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
9836
        // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
9837
        // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
9838
15.2k
        if (!(g.LastItemData.InFlags & ImGuiItemFlags_NoNav))
9839
8.91k
        {
9840
8.91k
            window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent);
9841
8.91k
            if (g.NavId == id || g.NavAnyRequest)
9842
452
                if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
9843
5
                    if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened))
9844
5
                        NavProcessItem();
9845
8.91k
        }
9846
9847
        // [DEBUG] People keep stumbling on this problem and using "" as identifier in the root of a window instead of "##something".
9848
        // Empty identifier are valid and useful in a small amount of cases, but 99.9% of the time you want to use "##something".
9849
        // READ THE FAQ: https://dearimgui.org/faq
9850
15.2k
        IM_ASSERT(id != window->ID && "Cannot have an empty ID at the root of a window. If you need an empty label, use ## and read the FAQ about how the ID Stack works!");
9851
15.2k
    }
9852
18.3k
    g.NextItemData.Flags = ImGuiNextItemDataFlags_None;
9853
9854
#ifdef IMGUI_ENABLE_TEST_ENGINE
9855
    if (id != 0)
9856
        IMGUI_TEST_ENGINE_ITEM_ADD(nav_bb_arg ? *nav_bb_arg : bb, id);
9857
#endif
9858
9859
    // Clipping test
9860
    // (FIXME: This is a modified copy of IsClippedEx() so we can reuse the is_rect_visible value)
9861
    //const bool is_clipped = IsClippedEx(bb, id);
9862
    //if (is_clipped)
9863
    //    return false;
9864
18.3k
    const bool is_rect_visible = bb.Overlaps(window->ClipRect);
9865
18.3k
    if (!is_rect_visible)
9866
2.81k
        if (id == 0 || (id != g.ActiveId && id != g.NavId))
9867
2.81k
            if (!g.LogEnabled)
9868
2.81k
                return false;
9869
9870
    // [DEBUG]
9871
15.4k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9872
15.4k
    if (id != 0 && id == g.DebugLocateId)
9873
0
        DebugLocateItemResolveWithLastItem();
9874
15.4k
#endif
9875
    //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
9876
9877
    // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
9878
15.4k
    if (is_rect_visible)
9879
15.4k
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Visible;
9880
15.4k
    if (IsMouseHoveringRect(bb.Min, bb.Max))
9881
10
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect;
9882
15.4k
    return true;
9883
18.3k
}
9884
9885
// Gets back to previous line and continue with horizontal layout
9886
//      offset_from_start_x == 0 : follow right after previous item
9887
//      offset_from_start_x != 0 : align to specified x position (relative to window/group left)
9888
//      spacing_w < 0            : use default spacing if pos_x == 0, no spacing if pos_x != 0
9889
//      spacing_w >= 0           : enforce spacing amount
9890
void ImGui::SameLine(float offset_from_start_x, float spacing_w)
9891
0
{
9892
0
    ImGuiContext& g = *GImGui;
9893
0
    ImGuiWindow* window = g.CurrentWindow;
9894
0
    if (window->SkipItems)
9895
0
        return;
9896
9897
0
    if (offset_from_start_x != 0.0f)
9898
0
    {
9899
0
        if (spacing_w < 0.0f)
9900
0
            spacing_w = 0.0f;
9901
0
        window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
9902
0
        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
9903
0
    }
9904
0
    else
9905
0
    {
9906
0
        if (spacing_w < 0.0f)
9907
0
            spacing_w = g.Style.ItemSpacing.x;
9908
0
        window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
9909
0
        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
9910
0
    }
9911
0
    window->DC.CurrLineSize = window->DC.PrevLineSize;
9912
0
    window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
9913
0
    window->DC.IsSameLine = true;
9914
0
}
9915
9916
ImVec2 ImGui::GetCursorScreenPos()
9917
4.51k
{
9918
4.51k
    ImGuiWindow* window = GetCurrentWindowRead();
9919
4.51k
    return window->DC.CursorPos;
9920
4.51k
}
9921
9922
// 2022/08/05: Setting cursor position also extend boundaries (via modifying CursorMaxPos) used to compute window size, group size etc.
9923
// I believe this was is a judicious choice but it's probably being relied upon (it has been the case since 1.31 and 1.50)
9924
// It would be sane if we requested user to use SetCursorPos() + Dummy(ImVec2(0,0)) to extend CursorMaxPos...
9925
void ImGui::SetCursorScreenPos(const ImVec2& pos)
9926
0
{
9927
0
    ImGuiWindow* window = GetCurrentWindow();
9928
0
    window->DC.CursorPos = pos;
9929
    //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
9930
0
    window->DC.IsSetPos = true;
9931
0
}
9932
9933
// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
9934
// Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'.
9935
ImVec2 ImGui::GetCursorPos()
9936
0
{
9937
0
    ImGuiWindow* window = GetCurrentWindowRead();
9938
0
    return window->DC.CursorPos - window->Pos + window->Scroll;
9939
0
}
9940
9941
float ImGui::GetCursorPosX()
9942
0
{
9943
0
    ImGuiWindow* window = GetCurrentWindowRead();
9944
0
    return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
9945
0
}
9946
9947
float ImGui::GetCursorPosY()
9948
0
{
9949
0
    ImGuiWindow* window = GetCurrentWindowRead();
9950
0
    return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
9951
0
}
9952
9953
void ImGui::SetCursorPos(const ImVec2& local_pos)
9954
0
{
9955
0
    ImGuiWindow* window = GetCurrentWindow();
9956
0
    window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
9957
    //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
9958
0
    window->DC.IsSetPos = true;
9959
0
}
9960
9961
void ImGui::SetCursorPosX(float x)
9962
0
{
9963
0
    ImGuiWindow* window = GetCurrentWindow();
9964
0
    window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
9965
    //window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
9966
0
    window->DC.IsSetPos = true;
9967
0
}
9968
9969
void ImGui::SetCursorPosY(float y)
9970
0
{
9971
0
    ImGuiWindow* window = GetCurrentWindow();
9972
0
    window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
9973
    //window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
9974
0
    window->DC.IsSetPos = true;
9975
0
}
9976
9977
ImVec2 ImGui::GetCursorStartPos()
9978
0
{
9979
0
    ImGuiWindow* window = GetCurrentWindowRead();
9980
0
    return window->DC.CursorStartPos - window->Pos;
9981
0
}
9982
9983
void ImGui::Indent(float indent_w)
9984
0
{
9985
0
    ImGuiContext& g = *GImGui;
9986
0
    ImGuiWindow* window = GetCurrentWindow();
9987
0
    window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
9988
0
    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
9989
0
}
9990
9991
void ImGui::Unindent(float indent_w)
9992
0
{
9993
0
    ImGuiContext& g = *GImGui;
9994
0
    ImGuiWindow* window = GetCurrentWindow();
9995
0
    window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
9996
0
    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
9997
0
}
9998
9999
// Affect large frame+labels widgets only.
10000
void ImGui::SetNextItemWidth(float item_width)
10001
0
{
10002
0
    ImGuiContext& g = *GImGui;
10003
0
    g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth;
10004
0
    g.NextItemData.Width = item_width;
10005
0
}
10006
10007
// FIXME: Remove the == 0.0f behavior?
10008
void ImGui::PushItemWidth(float item_width)
10009
0
{
10010
0
    ImGuiContext& g = *GImGui;
10011
0
    ImGuiWindow* window = g.CurrentWindow;
10012
0
    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
10013
0
    window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
10014
0
    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
10015
0
}
10016
10017
void ImGui::PushMultiItemsWidths(int components, float w_full)
10018
0
{
10019
0
    ImGuiContext& g = *GImGui;
10020
0
    ImGuiWindow* window = g.CurrentWindow;
10021
0
    const ImGuiStyle& style = g.Style;
10022
0
    const float w_item_one  = ImMax(1.0f, IM_FLOOR((w_full - (style.ItemInnerSpacing.x) * (components - 1)) / (float)components));
10023
0
    const float w_item_last = ImMax(1.0f, IM_FLOOR(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components - 1)));
10024
0
    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
10025
0
    window->DC.ItemWidthStack.push_back(w_item_last);
10026
0
    for (int i = 0; i < components - 2; i++)
10027
0
        window->DC.ItemWidthStack.push_back(w_item_one);
10028
0
    window->DC.ItemWidth = (components == 1) ? w_item_last : w_item_one;
10029
0
    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
10030
0
}
10031
10032
void ImGui::PopItemWidth()
10033
0
{
10034
0
    ImGuiWindow* window = GetCurrentWindow();
10035
0
    window->DC.ItemWidth = window->DC.ItemWidthStack.back();
10036
0
    window->DC.ItemWidthStack.pop_back();
10037
0
}
10038
10039
// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
10040
// The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
10041
float ImGui::CalcItemWidth()
10042
0
{
10043
0
    ImGuiContext& g = *GImGui;
10044
0
    ImGuiWindow* window = g.CurrentWindow;
10045
0
    float w;
10046
0
    if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth)
10047
0
        w = g.NextItemData.Width;
10048
0
    else
10049
0
        w = window->DC.ItemWidth;
10050
0
    if (w < 0.0f)
10051
0
    {
10052
0
        float region_max_x = GetContentRegionMaxAbs().x;
10053
0
        w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w);
10054
0
    }
10055
0
    w = IM_FLOOR(w);
10056
0
    return w;
10057
0
}
10058
10059
// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
10060
// Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
10061
// Note that only CalcItemWidth() is publicly exposed.
10062
// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
10063
ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
10064
0
{
10065
0
    ImGuiContext& g = *GImGui;
10066
0
    ImGuiWindow* window = g.CurrentWindow;
10067
10068
0
    ImVec2 region_max;
10069
0
    if (size.x < 0.0f || size.y < 0.0f)
10070
0
        region_max = GetContentRegionMaxAbs();
10071
10072
0
    if (size.x == 0.0f)
10073
0
        size.x = default_w;
10074
0
    else if (size.x < 0.0f)
10075
0
        size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x + size.x);
10076
10077
0
    if (size.y == 0.0f)
10078
0
        size.y = default_h;
10079
0
    else if (size.y < 0.0f)
10080
0
        size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y + size.y);
10081
10082
0
    return size;
10083
0
}
10084
10085
float ImGui::GetTextLineHeight()
10086
0
{
10087
0
    ImGuiContext& g = *GImGui;
10088
0
    return g.FontSize;
10089
0
}
10090
10091
float ImGui::GetTextLineHeightWithSpacing()
10092
3.00k
{
10093
3.00k
    ImGuiContext& g = *GImGui;
10094
3.00k
    return g.FontSize + g.Style.ItemSpacing.y;
10095
3.00k
}
10096
10097
float ImGui::GetFrameHeight()
10098
0
{
10099
0
    ImGuiContext& g = *GImGui;
10100
0
    return g.FontSize + g.Style.FramePadding.y * 2.0f;
10101
0
}
10102
10103
float ImGui::GetFrameHeightWithSpacing()
10104
0
{
10105
0
    ImGuiContext& g = *GImGui;
10106
0
    return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
10107
0
}
10108
10109
// FIXME: All the Contents Region function are messy or misleading. WE WILL AIM TO OBSOLETE ALL OF THEM WITH A NEW "WORK RECT" API. Thanks for your patience!
10110
10111
// FIXME: This is in window space (not screen space!).
10112
ImVec2 ImGui::GetContentRegionMax()
10113
0
{
10114
0
    ImGuiContext& g = *GImGui;
10115
0
    ImGuiWindow* window = g.CurrentWindow;
10116
0
    ImVec2 mx = window->ContentRegionRect.Max - window->Pos;
10117
0
    if (window->DC.CurrentColumns || g.CurrentTable)
10118
0
        mx.x = window->WorkRect.Max.x - window->Pos.x;
10119
0
    return mx;
10120
0
}
10121
10122
// [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features.
10123
ImVec2 ImGui::GetContentRegionMaxAbs()
10124
3.00k
{
10125
3.00k
    ImGuiContext& g = *GImGui;
10126
3.00k
    ImGuiWindow* window = g.CurrentWindow;
10127
3.00k
    ImVec2 mx = window->ContentRegionRect.Max;
10128
3.00k
    if (window->DC.CurrentColumns || g.CurrentTable)
10129
0
        mx.x = window->WorkRect.Max.x;
10130
3.00k
    return mx;
10131
3.00k
}
10132
10133
ImVec2 ImGui::GetContentRegionAvail()
10134
3.00k
{
10135
3.00k
    ImGuiWindow* window = GImGui->CurrentWindow;
10136
3.00k
    return GetContentRegionMaxAbs() - window->DC.CursorPos;
10137
3.00k
}
10138
10139
// In window space (not screen space!)
10140
ImVec2 ImGui::GetWindowContentRegionMin()
10141
0
{
10142
0
    ImGuiWindow* window = GImGui->CurrentWindow;
10143
0
    return window->ContentRegionRect.Min - window->Pos;
10144
0
}
10145
10146
ImVec2 ImGui::GetWindowContentRegionMax()
10147
3.00k
{
10148
3.00k
    ImGuiWindow* window = GImGui->CurrentWindow;
10149
3.00k
    return window->ContentRegionRect.Max - window->Pos;
10150
3.00k
}
10151
10152
// Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
10153
// Groups are currently a mishmash of functionalities which should perhaps be clarified and separated.
10154
// FIXME-OPT: Could we safely early out on ->SkipItems?
10155
void ImGui::BeginGroup()
10156
0
{
10157
0
    ImGuiContext& g = *GImGui;
10158
0
    ImGuiWindow* window = g.CurrentWindow;
10159
10160
0
    g.GroupStack.resize(g.GroupStack.Size + 1);
10161
0
    ImGuiGroupData& group_data = g.GroupStack.back();
10162
0
    group_data.WindowID = window->ID;
10163
0
    group_data.BackupCursorPos = window->DC.CursorPos;
10164
0
    group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
10165
0
    group_data.BackupIndent = window->DC.Indent;
10166
0
    group_data.BackupGroupOffset = window->DC.GroupOffset;
10167
0
    group_data.BackupCurrLineSize = window->DC.CurrLineSize;
10168
0
    group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
10169
0
    group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
10170
0
    group_data.BackupHoveredIdIsAlive = g.HoveredId != 0;
10171
0
    group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;
10172
0
    group_data.EmitItem = true;
10173
10174
0
    window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
10175
0
    window->DC.Indent = window->DC.GroupOffset;
10176
0
    window->DC.CursorMaxPos = window->DC.CursorPos;
10177
0
    window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
10178
0
    if (g.LogEnabled)
10179
0
        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
10180
0
}
10181
10182
void ImGui::EndGroup()
10183
0
{
10184
0
    ImGuiContext& g = *GImGui;
10185
0
    ImGuiWindow* window = g.CurrentWindow;
10186
0
    IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls
10187
10188
0
    ImGuiGroupData& group_data = g.GroupStack.back();
10189
0
    IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window?
10190
10191
0
    if (window->DC.IsSetPos)
10192
0
        ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
10193
10194
0
    ImRect group_bb(group_data.BackupCursorPos, ImMax(window->DC.CursorMaxPos, group_data.BackupCursorPos));
10195
10196
0
    window->DC.CursorPos = group_data.BackupCursorPos;
10197
0
    window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
10198
0
    window->DC.Indent = group_data.BackupIndent;
10199
0
    window->DC.GroupOffset = group_data.BackupGroupOffset;
10200
0
    window->DC.CurrLineSize = group_data.BackupCurrLineSize;
10201
0
    window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
10202
0
    if (g.LogEnabled)
10203
0
        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
10204
10205
0
    if (!group_data.EmitItem)
10206
0
    {
10207
0
        g.GroupStack.pop_back();
10208
0
        return;
10209
0
    }
10210
10211
0
    window->DC.CurrLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset);      // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
10212
0
    ItemSize(group_bb.GetSize());
10213
0
    ItemAdd(group_bb, 0, NULL, ImGuiItemFlags_NoTabStop);
10214
10215
    // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group.
10216
    // It would be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets.
10217
    // Also if you grep for LastItemId you'll notice it is only used in that context.
10218
    // (The two tests not the same because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.)
10219
0
    const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
10220
0
    const bool group_contains_prev_active_id = (group_data.BackupActiveIdPreviousFrameIsAlive == false) && (g.ActiveIdPreviousFrameIsAlive == true);
10221
0
    if (group_contains_curr_active_id)
10222
0
        g.LastItemData.ID = g.ActiveId;
10223
0
    else if (group_contains_prev_active_id)
10224
0
        g.LastItemData.ID = g.ActiveIdPreviousFrame;
10225
0
    g.LastItemData.Rect = group_bb;
10226
10227
    // Forward Hovered flag
10228
0
    const bool group_contains_curr_hovered_id = (group_data.BackupHoveredIdIsAlive == false) && g.HoveredId != 0;
10229
0
    if (group_contains_curr_hovered_id)
10230
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
10231
10232
    // Forward Edited flag
10233
0
    if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)
10234
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
10235
10236
    // Forward Deactivated flag
10237
0
    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
10238
0
    if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame)
10239
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Deactivated;
10240
10241
0
    g.GroupStack.pop_back();
10242
    //window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255));   // [Debug]
10243
0
}
10244
10245
10246
//-----------------------------------------------------------------------------
10247
// [SECTION] SCROLLING
10248
//-----------------------------------------------------------------------------
10249
10250
// Helper to snap on edges when aiming at an item very close to the edge,
10251
// So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling.
10252
// When we refactor the scrolling API this may be configurable with a flag?
10253
// Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default.
10254
static float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio)
10255
0
{
10256
0
    if (target <= snap_min + snap_threshold)
10257
0
        return ImLerp(snap_min, target, center_ratio);
10258
0
    if (target >= snap_max - snap_threshold)
10259
0
        return ImLerp(target, snap_max, center_ratio);
10260
0
    return target;
10261
0
}
10262
10263
static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
10264
9.00k
{
10265
9.00k
    ImVec2 scroll = window->Scroll;
10266
9.00k
    ImVec2 decoration_size(window->DecoOuterSizeX1 + window->DecoInnerSizeX1 + window->DecoOuterSizeX2, window->DecoOuterSizeY1 + window->DecoInnerSizeY1 + window->DecoOuterSizeY2);
10267
27.0k
    for (int axis = 0; axis < 2; axis++)
10268
18.0k
    {
10269
18.0k
        if (window->ScrollTarget[axis] < FLT_MAX)
10270
2.85k
        {
10271
2.85k
            float center_ratio = window->ScrollTargetCenterRatio[axis];
10272
2.85k
            float scroll_target = window->ScrollTarget[axis];
10273
2.85k
            if (window->ScrollTargetEdgeSnapDist[axis] > 0.0f)
10274
0
            {
10275
0
                float snap_min = 0.0f;
10276
0
                float snap_max = window->ScrollMax[axis] + window->SizeFull[axis] - decoration_size[axis];
10277
0
                scroll_target = CalcScrollEdgeSnap(scroll_target, snap_min, snap_max, window->ScrollTargetEdgeSnapDist[axis], center_ratio);
10278
0
            }
10279
2.85k
            scroll[axis] = scroll_target - center_ratio * (window->SizeFull[axis] - decoration_size[axis]);
10280
2.85k
        }
10281
18.0k
        scroll[axis] = IM_FLOOR(ImMax(scroll[axis], 0.0f));
10282
18.0k
        if (!window->Collapsed && !window->SkipItems)
10283
18.0k
            scroll[axis] = ImMin(scroll[axis], window->ScrollMax[axis]);
10284
18.0k
    }
10285
9.00k
    return scroll;
10286
9.00k
}
10287
10288
void ImGui::ScrollToItem(ImGuiScrollFlags flags)
10289
0
{
10290
0
    ImGuiContext& g = *GImGui;
10291
0
    ImGuiWindow* window = g.CurrentWindow;
10292
0
    ScrollToRectEx(window, g.LastItemData.NavRect, flags);
10293
0
}
10294
10295
void ImGui::ScrollToRect(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
10296
0
{
10297
0
    ScrollToRectEx(window, item_rect, flags);
10298
0
}
10299
10300
// Scroll to keep newly navigated item fully into view
10301
ImVec2 ImGui::ScrollToRectEx(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
10302
0
{
10303
0
    ImGuiContext& g = *GImGui;
10304
0
    ImRect scroll_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
10305
0
    scroll_rect.Min.x = ImMin(scroll_rect.Min.x + window->DecoInnerSizeX1, scroll_rect.Max.x);
10306
0
    scroll_rect.Min.y = ImMin(scroll_rect.Min.y + window->DecoInnerSizeY1, scroll_rect.Max.y);
10307
    //GetForegroundDrawList(window)->AddRect(item_rect.Min, item_rect.Max, IM_COL32(255,0,0,255), 0.0f, 0, 5.0f); // [DEBUG]
10308
    //GetForegroundDrawList(window)->AddRect(scroll_rect.Min, scroll_rect.Max, IM_COL32_WHITE); // [DEBUG]
10309
10310
    // Check that only one behavior is selected per axis
10311
0
    IM_ASSERT((flags & ImGuiScrollFlags_MaskX_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskX_));
10312
0
    IM_ASSERT((flags & ImGuiScrollFlags_MaskY_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskY_));
10313
10314
    // Defaults
10315
0
    ImGuiScrollFlags in_flags = flags;
10316
0
    if ((flags & ImGuiScrollFlags_MaskX_) == 0 && window->ScrollbarX)
10317
0
        flags |= ImGuiScrollFlags_KeepVisibleEdgeX;
10318
0
    if ((flags & ImGuiScrollFlags_MaskY_) == 0)
10319
0
        flags |= window->Appearing ? ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeY;
10320
10321
0
    const bool fully_visible_x = item_rect.Min.x >= scroll_rect.Min.x && item_rect.Max.x <= scroll_rect.Max.x;
10322
0
    const bool fully_visible_y = item_rect.Min.y >= scroll_rect.Min.y && item_rect.Max.y <= scroll_rect.Max.y;
10323
0
    const bool can_be_fully_visible_x = (item_rect.GetWidth() + g.Style.ItemSpacing.x * 2.0f) <= scroll_rect.GetWidth() || (window->AutoFitFramesX > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
10324
0
    const bool can_be_fully_visible_y = (item_rect.GetHeight() + g.Style.ItemSpacing.y * 2.0f) <= scroll_rect.GetHeight() || (window->AutoFitFramesY > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
10325
10326
0
    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeX) && !fully_visible_x)
10327
0
    {
10328
0
        if (item_rect.Min.x < scroll_rect.Min.x || !can_be_fully_visible_x)
10329
0
            SetScrollFromPosX(window, item_rect.Min.x - g.Style.ItemSpacing.x - window->Pos.x, 0.0f);
10330
0
        else if (item_rect.Max.x >= scroll_rect.Max.x)
10331
0
            SetScrollFromPosX(window, item_rect.Max.x + g.Style.ItemSpacing.x - window->Pos.x, 1.0f);
10332
0
    }
10333
0
    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterX) && !fully_visible_x) || (flags & ImGuiScrollFlags_AlwaysCenterX))
10334
0
    {
10335
0
        if (can_be_fully_visible_x)
10336
0
            SetScrollFromPosX(window, ImFloor((item_rect.Min.x + item_rect.Max.x) * 0.5f) - window->Pos.x, 0.5f);
10337
0
        else
10338
0
            SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x, 0.0f);
10339
0
    }
10340
10341
0
    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeY) && !fully_visible_y)
10342
0
    {
10343
0
        if (item_rect.Min.y < scroll_rect.Min.y || !can_be_fully_visible_y)
10344
0
            SetScrollFromPosY(window, item_rect.Min.y - g.Style.ItemSpacing.y - window->Pos.y, 0.0f);
10345
0
        else if (item_rect.Max.y >= scroll_rect.Max.y)
10346
0
            SetScrollFromPosY(window, item_rect.Max.y + g.Style.ItemSpacing.y - window->Pos.y, 1.0f);
10347
0
    }
10348
0
    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterY) && !fully_visible_y) || (flags & ImGuiScrollFlags_AlwaysCenterY))
10349
0
    {
10350
0
        if (can_be_fully_visible_y)
10351
0
            SetScrollFromPosY(window, ImFloor((item_rect.Min.y + item_rect.Max.y) * 0.5f) - window->Pos.y, 0.5f);
10352
0
        else
10353
0
            SetScrollFromPosY(window, item_rect.Min.y - window->Pos.y, 0.0f);
10354
0
    }
10355
10356
0
    ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
10357
0
    ImVec2 delta_scroll = next_scroll - window->Scroll;
10358
10359
    // Also scroll parent window to keep us into view if necessary
10360
0
    if (!(flags & ImGuiScrollFlags_NoScrollParent) && (window->Flags & ImGuiWindowFlags_ChildWindow))
10361
0
    {
10362
        // FIXME-SCROLL: May be an option?
10363
0
        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterX | ImGuiScrollFlags_KeepVisibleCenterX)) != 0)
10364
0
            in_flags = (in_flags & ~ImGuiScrollFlags_MaskX_) | ImGuiScrollFlags_KeepVisibleEdgeX;
10365
0
        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterY | ImGuiScrollFlags_KeepVisibleCenterY)) != 0)
10366
0
            in_flags = (in_flags & ~ImGuiScrollFlags_MaskY_) | ImGuiScrollFlags_KeepVisibleEdgeY;
10367
0
        delta_scroll += ScrollToRectEx(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll), in_flags);
10368
0
    }
10369
10370
0
    return delta_scroll;
10371
0
}
10372
10373
float ImGui::GetScrollX()
10374
4.66k
{
10375
4.66k
    ImGuiWindow* window = GImGui->CurrentWindow;
10376
4.66k
    return window->Scroll.x;
10377
4.66k
}
10378
10379
float ImGui::GetScrollY()
10380
4.66k
{
10381
4.66k
    ImGuiWindow* window = GImGui->CurrentWindow;
10382
4.66k
    return window->Scroll.y;
10383
4.66k
}
10384
10385
float ImGui::GetScrollMaxX()
10386
0
{
10387
0
    ImGuiWindow* window = GImGui->CurrentWindow;
10388
0
    return window->ScrollMax.x;
10389
0
}
10390
10391
float ImGui::GetScrollMaxY()
10392
0
{
10393
0
    ImGuiWindow* window = GImGui->CurrentWindow;
10394
0
    return window->ScrollMax.y;
10395
0
}
10396
10397
void ImGui::SetScrollX(ImGuiWindow* window, float scroll_x)
10398
1.69k
{
10399
1.69k
    window->ScrollTarget.x = scroll_x;
10400
1.69k
    window->ScrollTargetCenterRatio.x = 0.0f;
10401
1.69k
    window->ScrollTargetEdgeSnapDist.x = 0.0f;
10402
1.69k
}
10403
10404
void ImGui::SetScrollY(ImGuiWindow* window, float scroll_y)
10405
1.18k
{
10406
1.18k
    window->ScrollTarget.y = scroll_y;
10407
1.18k
    window->ScrollTargetCenterRatio.y = 0.0f;
10408
1.18k
    window->ScrollTargetEdgeSnapDist.y = 0.0f;
10409
1.18k
}
10410
10411
void ImGui::SetScrollX(float scroll_x)
10412
1.67k
{
10413
1.67k
    ImGuiContext& g = *GImGui;
10414
1.67k
    SetScrollX(g.CurrentWindow, scroll_x);
10415
1.67k
}
10416
10417
void ImGui::SetScrollY(float scroll_y)
10418
1.13k
{
10419
1.13k
    ImGuiContext& g = *GImGui;
10420
1.13k
    SetScrollY(g.CurrentWindow, scroll_y);
10421
1.13k
}
10422
10423
// Note that a local position will vary depending on initial scroll value,
10424
// This is a little bit confusing so bear with us:
10425
//  - local_pos = (absolution_pos - window->Pos)
10426
//  - So local_x/local_y are 0.0f for a position at the upper-left corner of a window,
10427
//    and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area.
10428
//  - They mostly exist because of legacy API.
10429
// Following the rules above, when trying to work with scrolling code, consider that:
10430
//  - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect!
10431
//  - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense
10432
// We store a target position so centering and clamping can occur on the next frame when we are guaranteed to have a known window size
10433
void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
10434
0
{
10435
0
    IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
10436
0
    window->ScrollTarget.x = IM_FLOOR(local_x - window->DecoOuterSizeX1 - window->DecoInnerSizeX1 + window->Scroll.x); // Convert local position to scroll offset
10437
0
    window->ScrollTargetCenterRatio.x = center_x_ratio;
10438
0
    window->ScrollTargetEdgeSnapDist.x = 0.0f;
10439
0
}
10440
10441
void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
10442
0
{
10443
0
    IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
10444
0
    window->ScrollTarget.y = IM_FLOOR(local_y - window->DecoOuterSizeY1 - window->DecoInnerSizeY1 + window->Scroll.y); // Convert local position to scroll offset
10445
0
    window->ScrollTargetCenterRatio.y = center_y_ratio;
10446
0
    window->ScrollTargetEdgeSnapDist.y = 0.0f;
10447
0
}
10448
10449
void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
10450
0
{
10451
0
    ImGuiContext& g = *GImGui;
10452
0
    SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio);
10453
0
}
10454
10455
void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
10456
0
{
10457
0
    ImGuiContext& g = *GImGui;
10458
0
    SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio);
10459
0
}
10460
10461
// center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
10462
void ImGui::SetScrollHereX(float center_x_ratio)
10463
0
{
10464
0
    ImGuiContext& g = *GImGui;
10465
0
    ImGuiWindow* window = g.CurrentWindow;
10466
0
    float spacing_x = ImMax(window->WindowPadding.x, g.Style.ItemSpacing.x);
10467
0
    float target_pos_x = ImLerp(g.LastItemData.Rect.Min.x - spacing_x, g.LastItemData.Rect.Max.x + spacing_x, center_x_ratio);
10468
0
    SetScrollFromPosX(window, target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos
10469
10470
    // Tweak: snap on edges when aiming at an item very close to the edge
10471
0
    window->ScrollTargetEdgeSnapDist.x = ImMax(0.0f, window->WindowPadding.x - spacing_x);
10472
0
}
10473
10474
// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
10475
void ImGui::SetScrollHereY(float center_y_ratio)
10476
0
{
10477
0
    ImGuiContext& g = *GImGui;
10478
0
    ImGuiWindow* window = g.CurrentWindow;
10479
0
    float spacing_y = ImMax(window->WindowPadding.y, g.Style.ItemSpacing.y);
10480
0
    float target_pos_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio);
10481
0
    SetScrollFromPosY(window, target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos
10482
10483
    // Tweak: snap on edges when aiming at an item very close to the edge
10484
0
    window->ScrollTargetEdgeSnapDist.y = ImMax(0.0f, window->WindowPadding.y - spacing_y);
10485
0
}
10486
10487
//-----------------------------------------------------------------------------
10488
// [SECTION] TOOLTIPS
10489
//-----------------------------------------------------------------------------
10490
10491
void ImGui::BeginTooltip()
10492
0
{
10493
0
    BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
10494
0
}
10495
10496
void ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags)
10497
0
{
10498
0
    ImGuiContext& g = *GImGui;
10499
10500
0
    if (g.DragDropWithinSource || g.DragDropWithinTarget)
10501
0
    {
10502
        // The default tooltip position is a little offset to give space to see the context menu (it's also clamped within the current viewport/monitor)
10503
        // In the context of a dragging tooltip we try to reduce that offset and we enforce following the cursor.
10504
        // Whatever we do we want to call SetNextWindowPos() to enforce a tooltip position and disable clipping the tooltip without our display area, like regular tooltip do.
10505
        //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
10506
0
        ImVec2 tooltip_pos = g.IO.MousePos + ImVec2(16 * g.Style.MouseCursorScale, 8 * g.Style.MouseCursorScale);
10507
0
        SetNextWindowPos(tooltip_pos);
10508
0
        SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
10509
        //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
10510
0
        tooltip_flags |= ImGuiTooltipFlags_OverridePreviousTooltip;
10511
0
    }
10512
10513
0
    char window_name[16];
10514
0
    ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
10515
0
    if (tooltip_flags & ImGuiTooltipFlags_OverridePreviousTooltip)
10516
0
        if (ImGuiWindow* window = FindWindowByName(window_name))
10517
0
            if (window->Active)
10518
0
            {
10519
                // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
10520
0
                window->Hidden = true;
10521
0
                window->HiddenFramesCanSkipItems = 1; // FIXME: This may not be necessary?
10522
0
                ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
10523
0
            }
10524
0
    ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDocking;
10525
0
    Begin(window_name, NULL, flags | extra_window_flags);
10526
0
}
10527
10528
void ImGui::EndTooltip()
10529
0
{
10530
0
    IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip);   // Mismatched BeginTooltip()/EndTooltip() calls
10531
0
    End();
10532
0
}
10533
10534
void ImGui::SetTooltipV(const char* fmt, va_list args)
10535
0
{
10536
0
    BeginTooltipEx(ImGuiTooltipFlags_OverridePreviousTooltip, ImGuiWindowFlags_None);
10537
0
    TextV(fmt, args);
10538
0
    EndTooltip();
10539
0
}
10540
10541
void ImGui::SetTooltip(const char* fmt, ...)
10542
0
{
10543
0
    va_list args;
10544
0
    va_start(args, fmt);
10545
0
    SetTooltipV(fmt, args);
10546
0
    va_end(args);
10547
0
}
10548
10549
//-----------------------------------------------------------------------------
10550
// [SECTION] POPUPS
10551
//-----------------------------------------------------------------------------
10552
10553
// Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel
10554
bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags)
10555
0
{
10556
0
    ImGuiContext& g = *GImGui;
10557
0
    if (popup_flags & ImGuiPopupFlags_AnyPopupId)
10558
0
    {
10559
        // Return true if any popup is open at the current BeginPopup() level of the popup stack
10560
        // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level.
10561
0
        IM_ASSERT(id == 0);
10562
0
        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
10563
0
            return g.OpenPopupStack.Size > 0;
10564
0
        else
10565
0
            return g.OpenPopupStack.Size > g.BeginPopupStack.Size;
10566
0
    }
10567
0
    else
10568
0
    {
10569
0
        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
10570
0
        {
10571
            // Return true if the popup is open anywhere in the popup stack
10572
0
            for (int n = 0; n < g.OpenPopupStack.Size; n++)
10573
0
                if (g.OpenPopupStack[n].PopupId == id)
10574
0
                    return true;
10575
0
            return false;
10576
0
        }
10577
0
        else
10578
0
        {
10579
            // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query)
10580
0
            return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
10581
0
        }
10582
0
    }
10583
0
}
10584
10585
bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags)
10586
0
{
10587
0
    ImGuiContext& g = *GImGui;
10588
0
    ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str_id);
10589
0
    if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0)
10590
0
        IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally
10591
0
    return IsPopupOpen(id, popup_flags);
10592
0
}
10593
10594
ImGuiWindow* ImGui::GetTopMostPopupModal()
10595
9.29k
{
10596
9.29k
    ImGuiContext& g = *GImGui;
10597
9.29k
    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
10598
0
        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
10599
0
            if (popup->Flags & ImGuiWindowFlags_Modal)
10600
0
                return popup;
10601
9.29k
    return NULL;
10602
9.29k
}
10603
10604
ImGuiWindow* ImGui::GetTopMostAndVisiblePopupModal()
10605
3.00k
{
10606
3.00k
    ImGuiContext& g = *GImGui;
10607
3.00k
    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
10608
0
        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
10609
0
            if ((popup->Flags & ImGuiWindowFlags_Modal) && IsWindowActiveAndVisible(popup))
10610
0
                return popup;
10611
3.00k
    return NULL;
10612
3.00k
}
10613
10614
void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags)
10615
0
{
10616
0
    ImGuiContext& g = *GImGui;
10617
0
    ImGuiID id = g.CurrentWindow->GetID(str_id);
10618
0
    IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopup(\"%s\" -> 0x%08X\n", str_id, id);
10619
0
    OpenPopupEx(id, popup_flags);
10620
0
}
10621
10622
void ImGui::OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags)
10623
0
{
10624
0
    OpenPopupEx(id, popup_flags);
10625
0
}
10626
10627
// Mark popup as open (toggle toward open state).
10628
// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
10629
// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
10630
// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
10631
void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags)
10632
0
{
10633
0
    ImGuiContext& g = *GImGui;
10634
0
    ImGuiWindow* parent_window = g.CurrentWindow;
10635
0
    const int current_stack_size = g.BeginPopupStack.Size;
10636
10637
0
    if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup)
10638
0
        if (IsPopupOpen(0u, ImGuiPopupFlags_AnyPopupId))
10639
0
            return;
10640
10641
0
    ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
10642
0
    popup_ref.PopupId = id;
10643
0
    popup_ref.Window = NULL;
10644
0
    popup_ref.BackupNavWindow = g.NavWindow;            // When popup closes focus may be restored to NavWindow (depend on window type).
10645
0
    popup_ref.OpenFrameCount = g.FrameCount;
10646
0
    popup_ref.OpenParentId = parent_window->IDStack.back();
10647
0
    popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
10648
0
    popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
10649
10650
0
    IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id);
10651
0
    if (g.OpenPopupStack.Size < current_stack_size + 1)
10652
0
    {
10653
0
        g.OpenPopupStack.push_back(popup_ref);
10654
0
    }
10655
0
    else
10656
0
    {
10657
        // Gently handle the user mistakenly calling OpenPopup() every frame. It is a programming mistake! However, if we were to run the regular code path, the ui
10658
        // would become completely unusable because the popup will always be in hidden-while-calculating-size state _while_ claiming focus. Which would be a very confusing
10659
        // situation for the programmer. Instead, we silently allow the popup to proceed, it will keep reappearing and the programming error will be more obvious to understand.
10660
0
        if (g.OpenPopupStack[current_stack_size].PopupId == id && g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1)
10661
0
        {
10662
0
            g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
10663
0
        }
10664
0
        else
10665
0
        {
10666
            // Close child popups if any, then flag popup for open/reopen
10667
0
            ClosePopupToLevel(current_stack_size, false);
10668
0
            g.OpenPopupStack.push_back(popup_ref);
10669
0
        }
10670
10671
        // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
10672
        // This is equivalent to what ClosePopupToLevel() does.
10673
        //if (g.OpenPopupStack[current_stack_size].PopupId == id)
10674
        //    FocusWindow(parent_window);
10675
0
    }
10676
0
}
10677
10678
// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
10679
// This function closes any popups that are over 'ref_window'.
10680
void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
10681
915
{
10682
915
    ImGuiContext& g = *GImGui;
10683
915
    if (g.OpenPopupStack.Size == 0)
10684
915
        return;
10685
10686
    // Don't close our own child popup windows.
10687
0
    int popup_count_to_keep = 0;
10688
0
    if (ref_window)
10689
0
    {
10690
        // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
10691
0
        for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
10692
0
        {
10693
0
            ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
10694
0
            if (!popup.Window)
10695
0
                continue;
10696
0
            IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
10697
0
            if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow)
10698
0
                continue;
10699
10700
            // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow)
10701
            // - With this stack of window, clicking/focusing Popup1 will close Popup2 and Popup3:
10702
            //     Window -> Popup1 -> Popup2 -> Popup3
10703
            // - Each popups may contain child windows, which is why we compare ->RootWindowDockTree!
10704
            //     Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child
10705
0
            bool ref_window_is_descendent_of_popup = false;
10706
0
            for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++)
10707
0
                if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window)
10708
                    //if (popup_window->RootWindowDockTree == ref_window->RootWindowDockTree) // FIXME-MERGE
10709
0
                    if (IsWindowWithinBeginStackOf(ref_window, popup_window))
10710
0
                    {
10711
0
                        ref_window_is_descendent_of_popup = true;
10712
0
                        break;
10713
0
                    }
10714
0
            if (!ref_window_is_descendent_of_popup)
10715
0
                break;
10716
0
        }
10717
0
    }
10718
0
    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
10719
0
    {
10720
0
        IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window ? ref_window->Name : "<NULL>");
10721
0
        ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup);
10722
0
    }
10723
0
}
10724
10725
void ImGui::ClosePopupsExceptModals()
10726
0
{
10727
0
    ImGuiContext& g = *GImGui;
10728
10729
0
    int popup_count_to_keep;
10730
0
    for (popup_count_to_keep = g.OpenPopupStack.Size; popup_count_to_keep > 0; popup_count_to_keep--)
10731
0
    {
10732
0
        ImGuiWindow* window = g.OpenPopupStack[popup_count_to_keep - 1].Window;
10733
0
        if (!window || window->Flags & ImGuiWindowFlags_Modal)
10734
0
            break;
10735
0
    }
10736
0
    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
10737
0
        ClosePopupToLevel(popup_count_to_keep, true);
10738
0
}
10739
10740
void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
10741
0
{
10742
0
    ImGuiContext& g = *GImGui;
10743
0
    IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_focus_to_window_under_popup=%d\n", remaining, restore_focus_to_window_under_popup);
10744
0
    IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
10745
10746
    // Trim open popup stack
10747
0
    ImGuiWindow* popup_window = g.OpenPopupStack[remaining].Window;
10748
0
    ImGuiWindow* popup_backup_nav_window = g.OpenPopupStack[remaining].BackupNavWindow;
10749
0
    g.OpenPopupStack.resize(remaining);
10750
10751
0
    if (restore_focus_to_window_under_popup)
10752
0
    {
10753
0
        ImGuiWindow* focus_window = (popup_window && popup_window->Flags & ImGuiWindowFlags_ChildMenu) ? popup_window->ParentWindow : popup_backup_nav_window;
10754
0
        if (focus_window && !focus_window->WasActive && popup_window)
10755
0
        {
10756
            // Fallback
10757
0
            FocusTopMostWindowUnderOne(popup_window, NULL);
10758
0
        }
10759
0
        else
10760
0
        {
10761
0
            if (g.NavLayer == ImGuiNavLayer_Main && focus_window)
10762
0
                focus_window = NavRestoreLastChildNavWindow(focus_window);
10763
0
            FocusWindow(focus_window);
10764
0
        }
10765
0
    }
10766
0
}
10767
10768
// Close the popup we have begin-ed into.
10769
void ImGui::CloseCurrentPopup()
10770
0
{
10771
0
    ImGuiContext& g = *GImGui;
10772
0
    int popup_idx = g.BeginPopupStack.Size - 1;
10773
0
    if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
10774
0
        return;
10775
10776
    // Closing a menu closes its top-most parent popup (unless a modal)
10777
0
    while (popup_idx > 0)
10778
0
    {
10779
0
        ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
10780
0
        ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
10781
0
        bool close_parent = false;
10782
0
        if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
10783
0
            if (parent_popup_window && !(parent_popup_window->Flags & ImGuiWindowFlags_MenuBar))
10784
0
                close_parent = true;
10785
0
        if (!close_parent)
10786
0
            break;
10787
0
        popup_idx--;
10788
0
    }
10789
0
    IMGUI_DEBUG_LOG_POPUP("[popup] CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
10790
0
    ClosePopupToLevel(popup_idx, true);
10791
10792
    // A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
10793
    // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
10794
    // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
10795
0
    if (ImGuiWindow* window = g.NavWindow)
10796
0
        window->DC.NavHideHighlightOneFrame = true;
10797
0
}
10798
10799
// Attention! BeginPopup() adds default flags which BeginPopupEx()!
10800
bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags)
10801
0
{
10802
0
    ImGuiContext& g = *GImGui;
10803
0
    if (!IsPopupOpen(id, ImGuiPopupFlags_None))
10804
0
    {
10805
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
10806
0
        return false;
10807
0
    }
10808
10809
0
    char name[20];
10810
0
    if (flags & ImGuiWindowFlags_ChildMenu)
10811
0
        ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginMenuCount); // Recycle windows based on depth
10812
0
    else
10813
0
        ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
10814
10815
0
    flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoDocking;
10816
0
    bool is_open = Begin(name, NULL, flags);
10817
0
    if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
10818
0
        EndPopup();
10819
10820
0
    return is_open;
10821
0
}
10822
10823
bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
10824
0
{
10825
0
    ImGuiContext& g = *GImGui;
10826
0
    if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
10827
0
    {
10828
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
10829
0
        return false;
10830
0
    }
10831
0
    flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
10832
0
    ImGuiID id = g.CurrentWindow->GetID(str_id);
10833
0
    return BeginPopupEx(id, flags);
10834
0
}
10835
10836
// If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
10837
// Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup) so the actual value of *p_open is meaningless here.
10838
bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
10839
0
{
10840
0
    ImGuiContext& g = *GImGui;
10841
0
    ImGuiWindow* window = g.CurrentWindow;
10842
0
    const ImGuiID id = window->GetID(name);
10843
0
    if (!IsPopupOpen(id, ImGuiPopupFlags_None))
10844
0
    {
10845
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
10846
0
        return false;
10847
0
    }
10848
10849
    // Center modal windows by default for increased visibility
10850
    // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves)
10851
    // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
10852
0
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)
10853
0
    {
10854
0
        const ImGuiViewport* viewport = window->WasActive ? window->Viewport : GetMainViewport(); // FIXME-VIEWPORT: What may be our reference viewport?
10855
0
        SetNextWindowPos(viewport->GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f));
10856
0
    }
10857
10858
0
    flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking;
10859
0
    const bool is_open = Begin(name, p_open, flags);
10860
0
    if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
10861
0
    {
10862
0
        EndPopup();
10863
0
        if (is_open)
10864
0
            ClosePopupToLevel(g.BeginPopupStack.Size, true);
10865
0
        return false;
10866
0
    }
10867
0
    return is_open;
10868
0
}
10869
10870
void ImGui::EndPopup()
10871
0
{
10872
0
    ImGuiContext& g = *GImGui;
10873
0
    ImGuiWindow* window = g.CurrentWindow;
10874
0
    IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup);  // Mismatched BeginPopup()/EndPopup() calls
10875
0
    IM_ASSERT(g.BeginPopupStack.Size > 0);
10876
10877
    // Make all menus and popups wrap around for now, may need to expose that policy (e.g. focus scope could include wrap/loop policy flags used by new move requests)
10878
0
    if (g.NavWindow == window)
10879
0
        NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY);
10880
10881
    // Child-popups don't need to be laid out
10882
0
    IM_ASSERT(g.WithinEndChild == false);
10883
0
    if (window->Flags & ImGuiWindowFlags_ChildWindow)
10884
0
        g.WithinEndChild = true;
10885
0
    End();
10886
0
    g.WithinEndChild = false;
10887
0
}
10888
10889
// Helper to open a popup if mouse button is released over the item
10890
// - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup()
10891
void ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags)
10892
0
{
10893
0
    ImGuiContext& g = *GImGui;
10894
0
    ImGuiWindow* window = g.CurrentWindow;
10895
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
10896
0
    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
10897
0
    {
10898
0
        ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
10899
0
        IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
10900
0
        OpenPopupEx(id, popup_flags);
10901
0
    }
10902
0
}
10903
10904
// This is a helper to handle the simplest case of associating one named popup to one given widget.
10905
// - To create a popup associated to the last item, you generally want to pass a NULL value to str_id.
10906
// - To create a popup with a specific identifier, pass it in str_id.
10907
//    - This is useful when using using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call.
10908
//    - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id.
10909
// - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
10910
//   This is essentially the same as:
10911
//       id = str_id ? GetID(str_id) : GetItemID();
10912
//       OpenPopupOnItemClick(str_id, ImGuiPopupFlags_MouseButtonRight);
10913
//       return BeginPopup(id);
10914
//   Which is essentially the same as:
10915
//       id = str_id ? GetID(str_id) : GetItemID();
10916
//       if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
10917
//           OpenPopup(id);
10918
//       return BeginPopup(id);
10919
//   The main difference being that this is tweaked to avoid computing the ID twice.
10920
bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags)
10921
0
{
10922
0
    ImGuiContext& g = *GImGui;
10923
0
    ImGuiWindow* window = g.CurrentWindow;
10924
0
    if (window->SkipItems)
10925
0
        return false;
10926
0
    ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
10927
0
    IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
10928
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
10929
0
    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
10930
0
        OpenPopupEx(id, popup_flags);
10931
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
10932
0
}
10933
10934
bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags)
10935
0
{
10936
0
    ImGuiContext& g = *GImGui;
10937
0
    ImGuiWindow* window = g.CurrentWindow;
10938
0
    if (!str_id)
10939
0
        str_id = "window_context";
10940
0
    ImGuiID id = window->GetID(str_id);
10941
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
10942
0
    if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
10943
0
        if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered())
10944
0
            OpenPopupEx(id, popup_flags);
10945
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
10946
0
}
10947
10948
bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags)
10949
0
{
10950
0
    ImGuiContext& g = *GImGui;
10951
0
    ImGuiWindow* window = g.CurrentWindow;
10952
0
    if (!str_id)
10953
0
        str_id = "void_context";
10954
0
    ImGuiID id = window->GetID(str_id);
10955
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
10956
0
    if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
10957
0
        if (GetTopMostPopupModal() == NULL)
10958
0
            OpenPopupEx(id, popup_flags);
10959
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
10960
0
}
10961
10962
// r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.)
10963
// r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it.
10964
// (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor
10965
//  information are available, it may represent the entire platform monitor from the frame of reference of the current viewport.
10966
//  this allows us to have tooltips/popups displayed out of the parent viewport.)
10967
ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
10968
0
{
10969
0
    ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
10970
    //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
10971
    //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
10972
10973
    // Combo Box policy (we want a connecting edge)
10974
0
    if (policy == ImGuiPopupPositionPolicy_ComboBox)
10975
0
    {
10976
0
        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
10977
0
        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
10978
0
        {
10979
0
            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
10980
0
            if (n != -1 && dir == *last_dir) // Already tried this direction?
10981
0
                continue;
10982
0
            ImVec2 pos;
10983
0
            if (dir == ImGuiDir_Down)  pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y);          // Below, Toward Right (default)
10984
0
            if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
10985
0
            if (dir == ImGuiDir_Left)  pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
10986
0
            if (dir == ImGuiDir_Up)    pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
10987
0
            if (!r_outer.Contains(ImRect(pos, pos + size)))
10988
0
                continue;
10989
0
            *last_dir = dir;
10990
0
            return pos;
10991
0
        }
10992
0
    }
10993
10994
    // Tooltip and Default popup policy
10995
    // (Always first try the direction we used on the last frame, if any)
10996
0
    if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default)
10997
0
    {
10998
0
        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
10999
0
        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
11000
0
        {
11001
0
            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
11002
0
            if (n != -1 && dir == *last_dir) // Already tried this direction?
11003
0
                continue;
11004
11005
0
            const float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x);
11006
0
            const float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y);
11007
11008
            // If there's not enough room on one axis, there's no point in positioning on a side on this axis (e.g. when not enough width, use a top/bottom position to maximize available width)
11009
0
            if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right))
11010
0
                continue;
11011
0
            if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down))
11012
0
                continue;
11013
11014
0
            ImVec2 pos;
11015
0
            pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
11016
0
            pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
11017
11018
            // Clamp top-left corner of popup
11019
0
            pos.x = ImMax(pos.x, r_outer.Min.x);
11020
0
            pos.y = ImMax(pos.y, r_outer.Min.y);
11021
11022
0
            *last_dir = dir;
11023
0
            return pos;
11024
0
        }
11025
0
    }
11026
11027
    // Fallback when not enough room:
11028
0
    *last_dir = ImGuiDir_None;
11029
11030
    // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
11031
0
    if (policy == ImGuiPopupPositionPolicy_Tooltip)
11032
0
        return ref_pos + ImVec2(2, 2);
11033
11034
    // Otherwise try to keep within display
11035
0
    ImVec2 pos = ref_pos;
11036
0
    pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
11037
0
    pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
11038
0
    return pos;
11039
0
}
11040
11041
// Note that this is used for popups, which can overlap the non work-area of individual viewports.
11042
ImRect ImGui::GetPopupAllowedExtentRect(ImGuiWindow* window)
11043
0
{
11044
0
    ImGuiContext& g = *GImGui;
11045
0
    ImRect r_screen;
11046
0
    if (window->ViewportAllowPlatformMonitorExtend >= 0)
11047
0
    {
11048
        // Extent with be in the frame of reference of the given viewport (so Min is likely to be negative here)
11049
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[window->ViewportAllowPlatformMonitorExtend];
11050
0
        r_screen.Min = monitor.WorkPos;
11051
0
        r_screen.Max = monitor.WorkPos + monitor.WorkSize;
11052
0
    }
11053
0
    else
11054
0
    {
11055
        // Use the full viewport area (not work area) for popups
11056
0
        r_screen = window->Viewport->GetMainRect();
11057
0
    }
11058
0
    ImVec2 padding = g.Style.DisplaySafeAreaPadding;
11059
0
    r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
11060
0
    return r_screen;
11061
0
}
11062
11063
ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
11064
0
{
11065
0
    ImGuiContext& g = *GImGui;
11066
11067
0
    ImRect r_outer = GetPopupAllowedExtentRect(window);
11068
0
    if (window->Flags & ImGuiWindowFlags_ChildMenu)
11069
0
    {
11070
        // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
11071
        // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
11072
0
        ImGuiWindow* parent_window = window->ParentWindow;
11073
0
        float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x).
11074
0
        ImRect r_avoid;
11075
0
        if (parent_window->DC.MenuBarAppending)
11076
0
            r_avoid = ImRect(-FLT_MAX, parent_window->ClipRect.Min.y, FLT_MAX, parent_window->ClipRect.Max.y); // Avoid parent menu-bar. If we wanted multi-line menu-bar, we may instead want to have the calling window setup e.g. a NextWindowData.PosConstraintAvoidRect field
11077
0
        else
11078
0
            r_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX);
11079
0
        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default);
11080
0
    }
11081
0
    if (window->Flags & ImGuiWindowFlags_Popup)
11082
0
    {
11083
0
        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, ImRect(window->Pos, window->Pos), ImGuiPopupPositionPolicy_Default); // Ideally we'd disable r_avoid here
11084
0
    }
11085
0
    if (window->Flags & ImGuiWindowFlags_Tooltip)
11086
0
    {
11087
        // Position tooltip (always follows mouse)
11088
0
        float sc = g.Style.MouseCursorScale;
11089
0
        ImVec2 ref_pos = NavCalcPreferredRefPos();
11090
0
        ImRect r_avoid;
11091
0
        if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
11092
0
            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
11093
0
        else
11094
0
            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * sc, ref_pos.y + 24 * sc); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
11095
0
        return FindBestWindowPosForPopupEx(ref_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Tooltip);
11096
0
    }
11097
0
    IM_ASSERT(0);
11098
0
    return window->Pos;
11099
0
}
11100
11101
//-----------------------------------------------------------------------------
11102
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
11103
//-----------------------------------------------------------------------------
11104
11105
// FIXME-NAV: The existence of SetNavID vs SetFocusID vs FocusWindow() needs to be clarified/reworked.
11106
// In our terminology those should be interchangeable, yet right now this is super confusing.
11107
// Those two functions are merely a legacy artifact, so at minimum naming should be clarified.
11108
11109
void ImGui::SetNavWindow(ImGuiWindow* window)
11110
903
{
11111
903
    ImGuiContext& g = *GImGui;
11112
903
    if (g.NavWindow != window)
11113
903
    {
11114
903
        IMGUI_DEBUG_LOG_FOCUS("[focus] SetNavWindow(\"%s\")\n", window ? window->Name : "<NULL>");
11115
903
        g.NavWindow = window;
11116
903
    }
11117
903
    g.NavInitRequest = g.NavMoveSubmitted = g.NavMoveScoringItems = false;
11118
903
    NavUpdateAnyRequestFlag();
11119
903
}
11120
11121
void ImGui::SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
11122
3
{
11123
3
    ImGuiContext& g = *GImGui;
11124
3
    IM_ASSERT(g.NavWindow != NULL);
11125
3
    IM_ASSERT(nav_layer == ImGuiNavLayer_Main || nav_layer == ImGuiNavLayer_Menu);
11126
3
    g.NavId = id;
11127
3
    g.NavLayer = nav_layer;
11128
3
    g.NavFocusScopeId = focus_scope_id;
11129
3
    g.NavWindow->NavLastIds[nav_layer] = id;
11130
3
    g.NavWindow->NavRectRel[nav_layer] = rect_rel;
11131
3
}
11132
11133
void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
11134
0
{
11135
0
    ImGuiContext& g = *GImGui;
11136
0
    IM_ASSERT(id != 0);
11137
11138
0
    if (g.NavWindow != window)
11139
0
       SetNavWindow(window);
11140
11141
    // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and g.CurrentFocusScopeId are valid.
11142
    // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
11143
0
    const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
11144
0
    g.NavId = id;
11145
0
    g.NavLayer = nav_layer;
11146
0
    g.NavFocusScopeId = g.CurrentFocusScopeId;
11147
0
    window->NavLastIds[nav_layer] = id;
11148
0
    if (g.LastItemData.ID == id)
11149
0
        window->NavRectRel[nav_layer] = WindowRectAbsToRel(window, g.LastItemData.NavRect);
11150
11151
0
    if (g.ActiveIdSource == ImGuiInputSource_Nav)
11152
0
        g.NavDisableMouseHover = true;
11153
0
    else
11154
0
        g.NavDisableHighlight = true;
11155
0
}
11156
11157
ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
11158
0
{
11159
0
    if (ImFabs(dx) > ImFabs(dy))
11160
0
        return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
11161
0
    return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
11162
0
}
11163
11164
static float inline NavScoreItemDistInterval(float a0, float a1, float b0, float b1)
11165
0
{
11166
0
    if (a1 < b0)
11167
0
        return a1 - b0;
11168
0
    if (b1 < a0)
11169
0
        return a0 - b1;
11170
0
    return 0.0f;
11171
0
}
11172
11173
static void inline NavClampRectToVisibleAreaForMoveDir(ImGuiDir move_dir, ImRect& r, const ImRect& clip_rect)
11174
0
{
11175
0
    if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
11176
0
    {
11177
0
        r.Min.y = ImClamp(r.Min.y, clip_rect.Min.y, clip_rect.Max.y);
11178
0
        r.Max.y = ImClamp(r.Max.y, clip_rect.Min.y, clip_rect.Max.y);
11179
0
    }
11180
0
    else // FIXME: PageUp/PageDown are leaving move_dir == None
11181
0
    {
11182
0
        r.Min.x = ImClamp(r.Min.x, clip_rect.Min.x, clip_rect.Max.x);
11183
0
        r.Max.x = ImClamp(r.Max.x, clip_rect.Min.x, clip_rect.Max.x);
11184
0
    }
11185
0
}
11186
11187
// Scoring function for gamepad/keyboard directional navigation. Based on https://gist.github.com/rygorous/6981057
11188
static bool ImGui::NavScoreItem(ImGuiNavItemData* result)
11189
0
{
11190
0
    ImGuiContext& g = *GImGui;
11191
0
    ImGuiWindow* window = g.CurrentWindow;
11192
0
    if (g.NavLayer != window->DC.NavLayerCurrent)
11193
0
        return false;
11194
11195
    // FIXME: Those are not good variables names
11196
0
    ImRect cand = g.LastItemData.NavRect;   // Current item nav rectangle
11197
0
    const ImRect curr = g.NavScoringRect;   // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width)
11198
0
    g.NavScoringDebugCount++;
11199
11200
    // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
11201
0
    if (window->ParentWindow == g.NavWindow)
11202
0
    {
11203
0
        IM_ASSERT((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened);
11204
0
        if (!window->ClipRect.Overlaps(cand))
11205
0
            return false;
11206
0
        cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
11207
0
    }
11208
11209
    // We perform scoring on items bounding box clipped by the current clipping rectangle on the other axis (clipping on our movement axis would give us equal scores for all clipped items)
11210
    // For example, this ensures that items in one column are not reached when moving vertically from items in another column.
11211
0
    NavClampRectToVisibleAreaForMoveDir(g.NavMoveClipDir, cand, window->ClipRect);
11212
11213
    // Compute distance between boxes
11214
    // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
11215
0
    float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
11216
0
    float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items
11217
0
    if (dby != 0.0f && dbx != 0.0f)
11218
0
        dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
11219
0
    float dist_box = ImFabs(dbx) + ImFabs(dby);
11220
11221
    // Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter)
11222
0
    float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
11223
0
    float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
11224
0
    float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
11225
11226
    // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
11227
0
    ImGuiDir quadrant;
11228
0
    float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
11229
0
    if (dbx != 0.0f || dby != 0.0f)
11230
0
    {
11231
        // For non-overlapping boxes, use distance between boxes
11232
0
        dax = dbx;
11233
0
        day = dby;
11234
0
        dist_axial = dist_box;
11235
0
        quadrant = ImGetDirQuadrantFromDelta(dbx, dby);
11236
0
    }
11237
0
    else if (dcx != 0.0f || dcy != 0.0f)
11238
0
    {
11239
        // For overlapping boxes with different centers, use distance between centers
11240
0
        dax = dcx;
11241
0
        day = dcy;
11242
0
        dist_axial = dist_center;
11243
0
        quadrant = ImGetDirQuadrantFromDelta(dcx, dcy);
11244
0
    }
11245
0
    else
11246
0
    {
11247
        // Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter)
11248
0
        quadrant = (g.LastItemData.ID < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
11249
0
    }
11250
11251
#if IMGUI_DEBUG_NAV_SCORING
11252
    char buf[128];
11253
    if (IsMouseHoveringRect(cand.Min, cand.Max))
11254
    {
11255
        ImFormatString(buf, IM_ARRAYSIZE(buf), "dbox (%.2f,%.2f->%.4f)\ndcen (%.2f,%.2f->%.4f)\nd (%.2f,%.2f->%.4f)\nnav %c, quadrant %c", dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "WENS"[g.NavMoveDir], "WENS"[quadrant]);
11256
        ImDrawList* draw_list = GetForegroundDrawList(window);
11257
        draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255,200,0,100));
11258
        draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255,255,0,200));
11259
        draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40,0,0,150));
11260
        draw_list->AddText(cand.Max, ~0U, buf);
11261
    }
11262
    else if (g.IO.KeyCtrl) // Hold to preview score in matching quadrant. Press C to rotate.
11263
    {
11264
        if (quadrant == g.NavMoveDir)
11265
        {
11266
            ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
11267
            ImDrawList* draw_list = GetForegroundDrawList(window);
11268
            draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 200));
11269
            draw_list->AddText(cand.Min, IM_COL32(255, 255, 255, 255), buf);
11270
        }
11271
    }
11272
#endif
11273
11274
    // Is it in the quadrant we're interested in moving to?
11275
0
    bool new_best = false;
11276
0
    const ImGuiDir move_dir = g.NavMoveDir;
11277
0
    if (quadrant == move_dir)
11278
0
    {
11279
        // Does it beat the current best candidate?
11280
0
        if (dist_box < result->DistBox)
11281
0
        {
11282
0
            result->DistBox = dist_box;
11283
0
            result->DistCenter = dist_center;
11284
0
            return true;
11285
0
        }
11286
0
        if (dist_box == result->DistBox)
11287
0
        {
11288
            // Try using distance between center points to break ties
11289
0
            if (dist_center < result->DistCenter)
11290
0
            {
11291
0
                result->DistCenter = dist_center;
11292
0
                new_best = true;
11293
0
            }
11294
0
            else if (dist_center == result->DistCenter)
11295
0
            {
11296
                // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
11297
                // (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index),
11298
                // this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis.
11299
0
                if (((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
11300
0
                    new_best = true;
11301
0
            }
11302
0
        }
11303
0
    }
11304
11305
    // Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches
11306
    // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
11307
    // This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too.
11308
    // 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward.
11309
    // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
11310
0
    if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial)  // Check axial match
11311
0
        if (g.NavLayer == ImGuiNavLayer_Menu && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
11312
0
            if ((move_dir == ImGuiDir_Left && dax < 0.0f) || (move_dir == ImGuiDir_Right && dax > 0.0f) || (move_dir == ImGuiDir_Up && day < 0.0f) || (move_dir == ImGuiDir_Down && day > 0.0f))
11313
0
            {
11314
0
                result->DistAxial = dist_axial;
11315
0
                new_best = true;
11316
0
            }
11317
11318
0
    return new_best;
11319
0
}
11320
11321
static void ImGui::NavApplyItemToResult(ImGuiNavItemData* result)
11322
0
{
11323
0
    ImGuiContext& g = *GImGui;
11324
0
    ImGuiWindow* window = g.CurrentWindow;
11325
0
    result->Window = window;
11326
0
    result->ID = g.LastItemData.ID;
11327
0
    result->FocusScopeId = g.CurrentFocusScopeId;
11328
0
    result->InFlags = g.LastItemData.InFlags;
11329
0
    result->RectRel = WindowRectAbsToRel(window, g.LastItemData.NavRect);
11330
0
}
11331
11332
// We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
11333
// This is called after LastItemData is set.
11334
static void ImGui::NavProcessItem()
11335
5
{
11336
5
    ImGuiContext& g = *GImGui;
11337
5
    ImGuiWindow* window = g.CurrentWindow;
11338
5
    const ImGuiID id = g.LastItemData.ID;
11339
5
    const ImRect nav_bb = g.LastItemData.NavRect;
11340
5
    const ImGuiItemFlags item_flags = g.LastItemData.InFlags;
11341
11342
    // Process Init Request
11343
5
    if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent && (item_flags & ImGuiItemFlags_Disabled) == 0)
11344
1
    {
11345
        // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
11346
1
        const bool candidate_for_nav_default_focus = (item_flags & ImGuiItemFlags_NoNavDefaultFocus) == 0;
11347
1
        if (candidate_for_nav_default_focus || g.NavInitResultId == 0)
11348
1
        {
11349
1
            g.NavInitResultId = id;
11350
1
            g.NavInitResultRectRel = WindowRectAbsToRel(window, nav_bb);
11351
1
        }
11352
1
        if (candidate_for_nav_default_focus)
11353
1
        {
11354
1
            g.NavInitRequest = false; // Found a match, clear request
11355
1
            NavUpdateAnyRequestFlag();
11356
1
        }
11357
1
    }
11358
11359
    // Process Move Request (scoring for navigation)
11360
    // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRect + scoring from a rect wrapped according to current wrapping policy)
11361
5
    if (g.NavMoveScoringItems)
11362
0
    {
11363
0
        const bool is_tab_stop = (item_flags & ImGuiItemFlags_Inputable) && (item_flags & (ImGuiItemFlags_NoTabStop | ImGuiItemFlags_Disabled)) == 0;
11364
0
        const bool is_tabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) != 0;
11365
0
        if (is_tabbing)
11366
0
        {
11367
0
            if (is_tab_stop || (g.NavMoveFlags & ImGuiNavMoveFlags_FocusApi))
11368
0
                NavProcessItemForTabbingRequest(id);
11369
0
        }
11370
0
        else if ((g.NavId != id || (g.NavMoveFlags & ImGuiNavMoveFlags_AllowCurrentNavId)) && !(item_flags & ImGuiItemFlags_Disabled))
11371
0
        {
11372
0
            ImGuiNavItemData* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
11373
0
            if (!is_tabbing)
11374
0
            {
11375
0
                if (NavScoreItem(result))
11376
0
                    NavApplyItemToResult(result);
11377
11378
                // Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
11379
0
                const float VISIBLE_RATIO = 0.70f;
11380
0
                if ((g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))
11381
0
                    if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO)
11382
0
                        if (NavScoreItem(&g.NavMoveResultLocalVisible))
11383
0
                            NavApplyItemToResult(&g.NavMoveResultLocalVisible);
11384
0
            }
11385
0
        }
11386
0
    }
11387
11388
    // Update window-relative bounding box of navigated item
11389
5
    if (g.NavId == id)
11390
2
    {
11391
2
        if (g.NavWindow != window)
11392
0
            SetNavWindow(window); // Always refresh g.NavWindow, because some operations such as FocusItem() may not have a window.
11393
2
        g.NavLayer = window->DC.NavLayerCurrent;
11394
2
        g.NavFocusScopeId = g.CurrentFocusScopeId;
11395
2
        g.NavIdIsAlive = true;
11396
2
        window->NavRectRel[window->DC.NavLayerCurrent] = WindowRectAbsToRel(window, nav_bb);    // Store item bounding box (relative to window position)
11397
2
    }
11398
5
}
11399
11400
// Handle "scoring" of an item for a tabbing/focusing request initiated by NavUpdateCreateTabbingRequest().
11401
// Note that SetKeyboardFocusHere() API calls are considered tabbing requests!
11402
// - Case 1: no nav/active id:    set result to first eligible item, stop storing.
11403
// - Case 2: tab forward:         on ref id set counter, on counter elapse store result
11404
// - Case 3: tab forward wrap:    set result to first eligible item (preemptively), on ref id set counter, on next frame if counter hasn't elapsed store result. // FIXME-TABBING: Could be done as a next-frame forwarded request
11405
// - Case 4: tab backward:        store all results, on ref id pick prev, stop storing
11406
// - Case 5: tab backward wrap:   store all results, on ref id if no result keep storing until last // FIXME-TABBING: Could be done as next-frame forwarded requested
11407
void ImGui::NavProcessItemForTabbingRequest(ImGuiID id)
11408
0
{
11409
0
    ImGuiContext& g = *GImGui;
11410
11411
    // Always store in NavMoveResultLocal (unlike directional request which uses NavMoveResultOther on sibling/flattened windows)
11412
0
    ImGuiNavItemData* result = &g.NavMoveResultLocal;
11413
0
    if (g.NavTabbingDir == +1)
11414
0
    {
11415
        // Tab Forward or SetKeyboardFocusHere() with >= 0
11416
0
        if (g.NavTabbingResultFirst.ID == 0)
11417
0
            NavApplyItemToResult(&g.NavTabbingResultFirst);
11418
0
        if (--g.NavTabbingCounter == 0)
11419
0
            NavMoveRequestResolveWithLastItem(result);
11420
0
        else if (g.NavId == id)
11421
0
            g.NavTabbingCounter = 1;
11422
0
    }
11423
0
    else if (g.NavTabbingDir == -1)
11424
0
    {
11425
        // Tab Backward
11426
0
        if (g.NavId == id)
11427
0
        {
11428
0
            if (result->ID)
11429
0
            {
11430
0
                g.NavMoveScoringItems = false;
11431
0
                NavUpdateAnyRequestFlag();
11432
0
            }
11433
0
        }
11434
0
        else
11435
0
        {
11436
0
            NavApplyItemToResult(result);
11437
0
        }
11438
0
    }
11439
0
    else if (g.NavTabbingDir == 0)
11440
0
    {
11441
        // Tab Init
11442
0
        if (g.NavTabbingResultFirst.ID == 0)
11443
0
            NavMoveRequestResolveWithLastItem(&g.NavTabbingResultFirst);
11444
0
    }
11445
0
}
11446
11447
bool ImGui::NavMoveRequestButNoResultYet()
11448
2.53k
{
11449
2.53k
    ImGuiContext& g = *GImGui;
11450
2.53k
    return g.NavMoveScoringItems && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
11451
2.53k
}
11452
11453
// FIXME: ScoringRect is not set
11454
void ImGui::NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
11455
149
{
11456
149
    ImGuiContext& g = *GImGui;
11457
149
    IM_ASSERT(g.NavWindow != NULL);
11458
11459
149
    if (move_flags & ImGuiNavMoveFlags_Tabbing)
11460
105
        move_flags |= ImGuiNavMoveFlags_AllowCurrentNavId;
11461
11462
149
    g.NavMoveSubmitted = g.NavMoveScoringItems = true;
11463
149
    g.NavMoveDir = move_dir;
11464
149
    g.NavMoveDirForDebug = move_dir;
11465
149
    g.NavMoveClipDir = clip_dir;
11466
149
    g.NavMoveFlags = move_flags;
11467
149
    g.NavMoveScrollFlags = scroll_flags;
11468
149
    g.NavMoveForwardToNextFrame = false;
11469
149
    g.NavMoveKeyMods = g.IO.KeyMods;
11470
149
    g.NavMoveResultLocal.Clear();
11471
149
    g.NavMoveResultLocalVisible.Clear();
11472
149
    g.NavMoveResultOther.Clear();
11473
149
    g.NavTabbingCounter = 0;
11474
149
    g.NavTabbingResultFirst.Clear();
11475
149
    NavUpdateAnyRequestFlag();
11476
149
}
11477
11478
void ImGui::NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result)
11479
0
{
11480
0
    ImGuiContext& g = *GImGui;
11481
0
    g.NavMoveScoringItems = false; // Ensure request doesn't need more processing
11482
0
    NavApplyItemToResult(result);
11483
0
    NavUpdateAnyRequestFlag();
11484
0
}
11485
11486
void ImGui::NavMoveRequestCancel()
11487
0
{
11488
0
    ImGuiContext& g = *GImGui;
11489
0
    g.NavMoveSubmitted = g.NavMoveScoringItems = false;
11490
0
    NavUpdateAnyRequestFlag();
11491
0
}
11492
11493
// Forward will reuse the move request again on the next frame (generally with modifications done to it)
11494
void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
11495
0
{
11496
0
    ImGuiContext& g = *GImGui;
11497
0
    IM_ASSERT(g.NavMoveForwardToNextFrame == false);
11498
0
    NavMoveRequestCancel();
11499
0
    g.NavMoveForwardToNextFrame = true;
11500
0
    g.NavMoveDir = move_dir;
11501
0
    g.NavMoveClipDir = clip_dir;
11502
0
    g.NavMoveFlags = move_flags | ImGuiNavMoveFlags_Forwarded;
11503
0
    g.NavMoveScrollFlags = scroll_flags;
11504
0
}
11505
11506
// Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire
11507
// popup is assembled and in case of appended popups it is not clear which EndPopup() call is final.
11508
void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags wrap_flags)
11509
0
{
11510
0
    ImGuiContext& g = *GImGui;
11511
0
    IM_ASSERT(wrap_flags != 0); // Call with _WrapX, _WrapY, _LoopX, _LoopY
11512
    // In theory we should test for NavMoveRequestButNoResultYet() but there's no point doing it, NavEndFrame() will do the same test
11513
0
    if (g.NavWindow == window && g.NavMoveScoringItems && g.NavLayer == ImGuiNavLayer_Main)
11514
0
        g.NavMoveFlags |= wrap_flags;
11515
0
}
11516
11517
// FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
11518
// This way we could find the last focused window among our children. It would be much less confusing this way?
11519
static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
11520
2.08k
{
11521
2.08k
    ImGuiWindow* parent = nav_window;
11522
4.17k
    while (parent && parent->RootWindow != parent && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
11523
2.08k
        parent = parent->ParentWindow;
11524
2.08k
    if (parent && parent != nav_window)
11525
2.08k
        parent->NavLastChildNavWindow = nav_window;
11526
2.08k
}
11527
11528
// Restore the last focused child.
11529
// Call when we are expected to land on the Main Layer (0) after FocusWindow()
11530
static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
11531
0
{
11532
0
    if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive)
11533
0
        return window->NavLastChildNavWindow;
11534
0
    if (window->DockNodeAsHost && window->DockNodeAsHost->TabBar)
11535
0
        if (ImGuiTabItem* tab = TabBarFindMostRecentlySelectedTabForActiveWindow(window->DockNodeAsHost->TabBar))
11536
0
            return tab->Window;
11537
0
    return window;
11538
0
}
11539
11540
void ImGui::NavRestoreLayer(ImGuiNavLayer layer)
11541
0
{
11542
0
    ImGuiContext& g = *GImGui;
11543
0
    if (layer == ImGuiNavLayer_Main)
11544
0
    {
11545
0
        ImGuiWindow* prev_nav_window = g.NavWindow;
11546
0
        g.NavWindow = NavRestoreLastChildNavWindow(g.NavWindow);    // FIXME-NAV: Should clear ongoing nav requests?
11547
0
        if (prev_nav_window)
11548
0
            IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name);
11549
0
    }
11550
0
    ImGuiWindow* window = g.NavWindow;
11551
0
    if (window->NavLastIds[layer] != 0)
11552
0
    {
11553
0
        SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]);
11554
0
    }
11555
0
    else
11556
0
    {
11557
0
        g.NavLayer = layer;
11558
0
        NavInitWindow(window, true);
11559
0
    }
11560
0
}
11561
11562
void ImGui::NavRestoreHighlightAfterMove()
11563
0
{
11564
0
    ImGuiContext& g = *GImGui;
11565
0
    g.NavDisableHighlight = false;
11566
0
    g.NavDisableMouseHover = g.NavMousePosDirty = true;
11567
0
}
11568
11569
static inline void ImGui::NavUpdateAnyRequestFlag()
11570
4.05k
{
11571
4.05k
    ImGuiContext& g = *GImGui;
11572
4.05k
    g.NavAnyRequest = g.NavMoveScoringItems || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
11573
4.05k
    if (g.NavAnyRequest)
11574
4.05k
        IM_ASSERT(g.NavWindow != NULL);
11575
4.05k
}
11576
11577
// This needs to be called before we submit any widget (aka in or before Begin)
11578
void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
11579
2
{
11580
    // FIXME: ChildWindow test here is wrong for docking
11581
2
    ImGuiContext& g = *GImGui;
11582
2
    IM_ASSERT(window == g.NavWindow);
11583
11584
2
    if (window->Flags & ImGuiWindowFlags_NoNavInputs)
11585
0
    {
11586
0
        g.NavId = 0;
11587
0
        g.NavFocusScopeId = window->NavRootFocusScopeId;
11588
0
        return;
11589
0
    }
11590
11591
2
    bool init_for_nav = false;
11592
2
    if (window == window->RootWindow || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
11593
2
        init_for_nav = true;
11594
2
    IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
11595
2
    if (init_for_nav)
11596
2
    {
11597
2
        SetNavID(0, g.NavLayer, window->NavRootFocusScopeId, ImRect());
11598
2
        g.NavInitRequest = true;
11599
2
        g.NavInitRequestFromMove = false;
11600
2
        g.NavInitResultId = 0;
11601
2
        g.NavInitResultRectRel = ImRect();
11602
2
        NavUpdateAnyRequestFlag();
11603
2
    }
11604
0
    else
11605
0
    {
11606
0
        g.NavId = window->NavLastIds[0];
11607
0
        g.NavFocusScopeId = window->NavRootFocusScopeId;
11608
0
    }
11609
2
}
11610
11611
static ImVec2 ImGui::NavCalcPreferredRefPos()
11612
0
{
11613
0
    ImGuiContext& g = *GImGui;
11614
0
    ImGuiWindow* window = g.NavWindow;
11615
0
    if (g.NavDisableHighlight || !g.NavDisableMouseHover || !window)
11616
0
    {
11617
        // Mouse (we need a fallback in case the mouse becomes invalid after being used)
11618
        // The +1.0f offset when stored by OpenPopupEx() allows reopening this or another popup (same or another mouse button) while not moving the mouse, it is pretty standard.
11619
        // In theory we could move that +1.0f offset in OpenPopupEx()
11620
0
        ImVec2 p = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : g.MouseLastValidPos;
11621
0
        return ImVec2(p.x + 1.0f, p.y);
11622
0
    }
11623
0
    else
11624
0
    {
11625
        // When navigation is active and mouse is disabled, pick a position around the bottom left of the currently navigated item
11626
        // Take account of upcoming scrolling (maybe set mouse pos should be done in EndFrame?)
11627
0
        ImRect rect_rel = WindowRectRelToAbs(window, window->NavRectRel[g.NavLayer]);
11628
0
        if (window->LastFrameActive != g.FrameCount && (window->ScrollTarget.x != FLT_MAX || window->ScrollTarget.y != FLT_MAX))
11629
0
        {
11630
0
            ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
11631
0
            rect_rel.Translate(window->Scroll - next_scroll);
11632
0
        }
11633
0
        ImVec2 pos = ImVec2(rect_rel.Min.x + ImMin(g.Style.FramePadding.x * 4, rect_rel.GetWidth()), rect_rel.Max.y - ImMin(g.Style.FramePadding.y, rect_rel.GetHeight()));
11634
0
        ImGuiViewport* viewport = window->Viewport;
11635
0
        return ImFloor(ImClamp(pos, viewport->Pos, viewport->Pos + viewport->Size)); // ImFloor() is important because non-integer mouse position application in backend might be lossy and result in undesirable non-zero delta.
11636
0
    }
11637
0
}
11638
11639
float ImGui::GetNavTweakPressedAmount(ImGuiAxis axis)
11640
0
{
11641
0
    ImGuiContext& g = *GImGui;
11642
0
    float repeat_delay, repeat_rate;
11643
0
    GetTypematicRepeatRate(ImGuiInputFlags_RepeatRateNavTweak, &repeat_delay, &repeat_rate);
11644
11645
0
    ImGuiKey key_less, key_more;
11646
0
    if (g.NavInputSource == ImGuiInputSource_Gamepad)
11647
0
    {
11648
0
        key_less = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadLeft : ImGuiKey_GamepadDpadUp;
11649
0
        key_more = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadRight : ImGuiKey_GamepadDpadDown;
11650
0
    }
11651
0
    else
11652
0
    {
11653
0
        key_less = (axis == ImGuiAxis_X) ? ImGuiKey_LeftArrow : ImGuiKey_UpArrow;
11654
0
        key_more = (axis == ImGuiAxis_X) ? ImGuiKey_RightArrow : ImGuiKey_DownArrow;
11655
0
    }
11656
0
    float amount = (float)GetKeyPressedAmount(key_more, repeat_delay, repeat_rate) - (float)GetKeyPressedAmount(key_less, repeat_delay, repeat_rate);
11657
0
    if (amount != 0.0f && IsKeyDown(key_less) && IsKeyDown(key_more)) // Cancel when opposite directions are held, regardless of repeat phase
11658
0
        amount = 0.0f;
11659
0
    return amount;
11660
0
}
11661
11662
static void ImGui::NavUpdate()
11663
3.00k
{
11664
3.00k
    ImGuiContext& g = *GImGui;
11665
3.00k
    ImGuiIO& io = g.IO;
11666
11667
3.00k
    io.WantSetMousePos = false;
11668
    //if (g.NavScoringDebugCount > 0) IMGUI_DEBUG_LOG_NAV("[nav] NavScoringDebugCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.NavScoringDebugCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest);
11669
11670
    // Set input source based on which keys are last pressed (as some features differs when used with Gamepad vs Keyboard)
11671
    // FIXME-NAV: Now that keys are separated maybe we can get rid of NavInputSource?
11672
3.00k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
11673
3.00k
    const ImGuiKey nav_gamepad_keys_to_change_source[] = { ImGuiKey_GamepadFaceRight, ImGuiKey_GamepadFaceLeft, ImGuiKey_GamepadFaceUp, ImGuiKey_GamepadFaceDown, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown };
11674
3.00k
    if (nav_gamepad_active)
11675
0
        for (ImGuiKey key : nav_gamepad_keys_to_change_source)
11676
0
            if (IsKeyDown(key))
11677
0
                g.NavInputSource = ImGuiInputSource_Gamepad;
11678
3.00k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
11679
3.00k
    const ImGuiKey nav_keyboard_keys_to_change_source[] = { ImGuiKey_Space, ImGuiKey_Enter, ImGuiKey_Escape, ImGuiKey_RightArrow, ImGuiKey_LeftArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow };
11680
3.00k
    if (nav_keyboard_active)
11681
3.00k
        for (ImGuiKey key : nav_keyboard_keys_to_change_source)
11682
21.0k
            if (IsKeyDown(key))
11683
194
                g.NavInputSource = ImGuiInputSource_Keyboard;
11684
11685
    // Process navigation init request (select first/default focus)
11686
3.00k
    if (g.NavInitResultId != 0)
11687
1
        NavInitRequestApplyResult();
11688
3.00k
    g.NavInitRequest = false;
11689
3.00k
    g.NavInitRequestFromMove = false;
11690
3.00k
    g.NavInitResultId = 0;
11691
3.00k
    g.NavJustMovedToId = 0;
11692
11693
    // Process navigation move request
11694
3.00k
    if (g.NavMoveSubmitted)
11695
144
        NavMoveRequestApplyResult();
11696
3.00k
    g.NavTabbingCounter = 0;
11697
3.00k
    g.NavMoveSubmitted = g.NavMoveScoringItems = false;
11698
11699
    // Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling)
11700
3.00k
    bool set_mouse_pos = false;
11701
3.00k
    if (g.NavMousePosDirty && g.NavIdIsAlive)
11702
0
        if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow)
11703
0
            set_mouse_pos = true;
11704
3.00k
    g.NavMousePosDirty = false;
11705
3.00k
    IM_ASSERT(g.NavLayer == ImGuiNavLayer_Main || g.NavLayer == ImGuiNavLayer_Menu);
11706
11707
    // Store our return window (for returning from Menu Layer to Main Layer) and clear it as soon as we step back in our own Layer 0
11708
3.00k
    if (g.NavWindow)
11709
2.08k
        NavSaveLastChildNavWindowIntoParent(g.NavWindow);
11710
3.00k
    if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main)
11711
0
        g.NavWindow->NavLastChildNavWindow = NULL;
11712
11713
    // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
11714
3.00k
    NavUpdateWindowing();
11715
11716
    // Set output flags for user application
11717
3.00k
    io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
11718
3.00k
    io.NavVisible = (io.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);
11719
11720
    // Process NavCancel input (to close a popup, get back to parent, clear focus)
11721
3.00k
    NavUpdateCancelRequest();
11722
11723
    // Process manual activation request
11724
3.00k
    g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavActivateInputId = 0;
11725
3.00k
    g.NavActivateFlags = ImGuiActivateFlags_None;
11726
3.00k
    if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
11727
0
    {
11728
0
        const bool activate_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Space)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadActivate));
11729
0
        const bool activate_pressed = activate_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Space, false)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadActivate, false)));
11730
0
        const bool input_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Enter)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadInput));
11731
0
        const bool input_pressed = input_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Enter, false)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadInput, false)));
11732
0
        if (g.ActiveId == 0 && activate_pressed)
11733
0
        {
11734
0
            g.NavActivateId = g.NavId;
11735
0
            g.NavActivateFlags = ImGuiActivateFlags_PreferTweak;
11736
0
        }
11737
0
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && input_pressed)
11738
0
        {
11739
0
            g.NavActivateInputId = g.NavId;
11740
0
            g.NavActivateFlags = ImGuiActivateFlags_PreferInput;
11741
0
        }
11742
0
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_down)
11743
0
            g.NavActivateDownId = g.NavId;
11744
0
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_pressed)
11745
0
            g.NavActivatePressedId = g.NavId;
11746
0
    }
11747
3.00k
    if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
11748
0
        g.NavDisableHighlight = true;
11749
3.00k
    if (g.NavActivateId != 0)
11750
3.00k
        IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
11751
11752
    // Process programmatic activation request
11753
    // FIXME-NAV: Those should eventually be queued (unlike focus they don't cancel each others)
11754
3.00k
    if (g.NavNextActivateId != 0)
11755
0
    {
11756
0
        if (g.NavNextActivateFlags & ImGuiActivateFlags_PreferInput)
11757
0
            g.NavActivateInputId = g.NavNextActivateId;
11758
0
        else
11759
0
            g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavNextActivateId;
11760
0
        g.NavActivateFlags = g.NavNextActivateFlags;
11761
0
    }
11762
3.00k
    g.NavNextActivateId = 0;
11763
11764
    // Process move requests
11765
3.00k
    NavUpdateCreateMoveRequest();
11766
3.00k
    if (g.NavMoveDir == ImGuiDir_None)
11767
2.95k
        NavUpdateCreateTabbingRequest();
11768
3.00k
    NavUpdateAnyRequestFlag();
11769
3.00k
    g.NavIdIsAlive = false;
11770
11771
    // Scrolling
11772
3.00k
    if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
11773
2.08k
    {
11774
        // *Fallback* manual-scroll with Nav directional keys when window has no navigable item
11775
2.08k
        ImGuiWindow* window = g.NavWindow;
11776
2.08k
        const float scroll_speed = IM_ROUND(window->CalcFontSize() * 100 * io.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
11777
2.08k
        const ImGuiDir move_dir = g.NavMoveDir;
11778
2.08k
        if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavHasScroll && move_dir != ImGuiDir_None)
11779
44
        {
11780
44
            if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
11781
23
                SetScrollX(window, ImFloor(window->Scroll.x + ((move_dir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
11782
44
            if (move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down)
11783
21
                SetScrollY(window, ImFloor(window->Scroll.y + ((move_dir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
11784
44
        }
11785
11786
        // *Normal* Manual scroll with LStick
11787
        // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
11788
2.08k
        if (nav_gamepad_active)
11789
0
        {
11790
0
            const ImVec2 scroll_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
11791
0
            const float tweak_factor = IsKeyDown(ImGuiKey_NavGamepadTweakSlow) ? 1.0f / 10.0f : IsKeyDown(ImGuiKey_NavGamepadTweakFast) ? 10.0f : 1.0f;
11792
0
            if (scroll_dir.x != 0.0f && window->ScrollbarX)
11793
0
                SetScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed * tweak_factor));
11794
0
            if (scroll_dir.y != 0.0f)
11795
0
                SetScrollY(window, ImFloor(window->Scroll.y + scroll_dir.y * scroll_speed * tweak_factor));
11796
0
        }
11797
2.08k
    }
11798
11799
    // Always prioritize mouse highlight if navigation is disabled
11800
3.00k
    if (!nav_keyboard_active && !nav_gamepad_active)
11801
0
    {
11802
0
        g.NavDisableHighlight = true;
11803
0
        g.NavDisableMouseHover = set_mouse_pos = false;
11804
0
    }
11805
11806
    // Update mouse position if requested
11807
    // (This will take into account the possibility that a Scroll was queued in the window to offset our absolute mouse position before scroll has been applied)
11808
3.00k
    if (set_mouse_pos && (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
11809
0
    {
11810
0
        io.MousePos = io.MousePosPrev = NavCalcPreferredRefPos();
11811
0
        io.WantSetMousePos = true;
11812
        //IMGUI_DEBUG_LOG_IO("SetMousePos: (%.1f,%.1f)\n", io.MousePos.x, io.MousePos.y);
11813
0
    }
11814
11815
    // [DEBUG]
11816
3.00k
    g.NavScoringDebugCount = 0;
11817
#if IMGUI_DEBUG_NAV_RECTS
11818
    if (g.NavWindow)
11819
    {
11820
        ImDrawList* draw_list = GetForegroundDrawList(g.NavWindow);
11821
        if (1) { for (int layer = 0; layer < 2; layer++) { ImRect r = WindowRectRelToAbs(g.NavWindow, g.NavWindow->NavRectRel[layer]); draw_list->AddRect(r.Min, r.Max, IM_COL32(255,200,0,255)); } } // [DEBUG]
11822
        if (1) { ImU32 col = (!g.NavWindow->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); draw_list->AddCircleFilled(p, 3.0f, col); draw_list->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); }
11823
    }
11824
#endif
11825
3.00k
}
11826
11827
void ImGui::NavInitRequestApplyResult()
11828
1
{
11829
    // In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void)
11830
1
    ImGuiContext& g = *GImGui;
11831
1
    if (!g.NavWindow)
11832
0
        return;
11833
11834
    // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
11835
    // FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently.
11836
1
    IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", g.NavInitResultId, g.NavLayer, g.NavWindow->Name);
11837
1
    SetNavID(g.NavInitResultId, g.NavLayer, 0, g.NavInitResultRectRel);
11838
1
    g.NavIdIsAlive = true; // Mark as alive from previous frame as we got a result
11839
1
    if (g.NavInitRequestFromMove)
11840
0
        NavRestoreHighlightAfterMove();
11841
1
}
11842
11843
void ImGui::NavUpdateCreateMoveRequest()
11844
3.00k
{
11845
3.00k
    ImGuiContext& g = *GImGui;
11846
3.00k
    ImGuiIO& io = g.IO;
11847
3.00k
    ImGuiWindow* window = g.NavWindow;
11848
3.00k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
11849
3.00k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
11850
11851
3.00k
    if (g.NavMoveForwardToNextFrame && window != NULL)
11852
0
    {
11853
        // Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window)
11854
        // (preserve most state, which were already set by the NavMoveRequestForward() function)
11855
0
        IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
11856
0
        IM_ASSERT(g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded);
11857
0
        IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir);
11858
0
    }
11859
3.00k
    else
11860
3.00k
    {
11861
        // Initiate directional inputs request
11862
3.00k
        g.NavMoveDir = ImGuiDir_None;
11863
3.00k
        g.NavMoveFlags = ImGuiNavMoveFlags_None;
11864
3.00k
        g.NavMoveScrollFlags = ImGuiScrollFlags_None;
11865
3.00k
        if (window && !g.NavWindowingTarget && !(window->Flags & ImGuiWindowFlags_NoNavInputs))
11866
2.08k
        {
11867
2.08k
            const ImGuiInputFlags repeat_mode = ImGuiInputFlags_Repeat | (ImGuiInputFlags)ImGuiInputFlags_RepeatRateNavMove;
11868
2.08k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Left)  && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadLeft,  ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_LeftArrow,  ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Left; }
11869
2.08k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Right) && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadRight, ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_RightArrow, ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Right; }
11870
2.08k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Up)    && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadUp,    ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_UpArrow,    ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Up; }
11871
2.08k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Down)  && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadDown,  ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_DownArrow,  ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Down; }
11872
2.08k
        }
11873
3.00k
        g.NavMoveClipDir = g.NavMoveDir;
11874
3.00k
        g.NavScoringNoClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
11875
3.00k
    }
11876
11877
    // Update PageUp/PageDown/Home/End scroll
11878
    // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
11879
3.00k
    float scoring_rect_offset_y = 0.0f;
11880
3.00k
    if (window && g.NavMoveDir == ImGuiDir_None && nav_keyboard_active)
11881
2.04k
        scoring_rect_offset_y = NavUpdatePageUpPageDown();
11882
3.00k
    if (scoring_rect_offset_y != 0.0f)
11883
0
    {
11884
0
        g.NavScoringNoClipRect = window->InnerRect;
11885
0
        g.NavScoringNoClipRect.TranslateY(scoring_rect_offset_y);
11886
0
    }
11887
11888
    // [DEBUG] Always send a request
11889
#if IMGUI_DEBUG_NAV_SCORING
11890
    if (io.KeyCtrl && IsKeyPressed(ImGuiKey_C))
11891
        g.NavMoveDirForDebug = (ImGuiDir)((g.NavMoveDirForDebug + 1) & 3);
11892
    if (io.KeyCtrl && g.NavMoveDir == ImGuiDir_None)
11893
    {
11894
        g.NavMoveDir = g.NavMoveDirForDebug;
11895
        g.NavMoveFlags |= ImGuiNavMoveFlags_DebugNoResult;
11896
    }
11897
#endif
11898
11899
    // Submit
11900
3.00k
    g.NavMoveForwardToNextFrame = false;
11901
3.00k
    if (g.NavMoveDir != ImGuiDir_None)
11902
44
        NavMoveRequestSubmit(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags);
11903
11904
    // Moving with no reference triggers an init request (will be used as a fallback if the direction fails to find a match)
11905
3.00k
    if (g.NavMoveSubmitted && g.NavId == 0)
11906
44
    {
11907
44
        IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "<NULL>", g.NavLayer);
11908
44
        g.NavInitRequest = g.NavInitRequestFromMove = true;
11909
44
        g.NavInitResultId = 0;
11910
44
        g.NavDisableHighlight = false;
11911
44
    }
11912
11913
    // When using gamepad, we project the reference nav bounding box into window visible area.
11914
    // This is to allow resuming navigation inside the visible area after doing a large amount of scrolling, since with gamepad all movements are relative
11915
    // (can't focus a visible object like we can with the mouse).
11916
3.00k
    if (g.NavMoveSubmitted && g.NavInputSource == ImGuiInputSource_Gamepad && g.NavLayer == ImGuiNavLayer_Main && window != NULL)// && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded))
11917
0
    {
11918
0
        bool clamp_x = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapX)) == 0;
11919
0
        bool clamp_y = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopY | ImGuiNavMoveFlags_WrapY)) == 0;
11920
0
        ImRect inner_rect_rel = WindowRectAbsToRel(window, ImRect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)));
11921
0
        if ((clamp_x || clamp_y) && !inner_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
11922
0
        {
11923
            //IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n");
11924
0
            float pad_x = ImMin(inner_rect_rel.GetWidth(), window->CalcFontSize() * 0.5f);
11925
0
            float pad_y = ImMin(inner_rect_rel.GetHeight(), window->CalcFontSize() * 0.5f); // Terrible approximation for the intent of starting navigation from first fully visible item
11926
0
            inner_rect_rel.Min.x = clamp_x ? (inner_rect_rel.Min.x + pad_x) : -FLT_MAX;
11927
0
            inner_rect_rel.Max.x = clamp_x ? (inner_rect_rel.Max.x - pad_x) : +FLT_MAX;
11928
0
            inner_rect_rel.Min.y = clamp_y ? (inner_rect_rel.Min.y + pad_y) : -FLT_MAX;
11929
0
            inner_rect_rel.Max.y = clamp_y ? (inner_rect_rel.Max.y - pad_y) : +FLT_MAX;
11930
0
            window->NavRectRel[g.NavLayer].ClipWithFull(inner_rect_rel);
11931
0
            g.NavId = 0;
11932
0
        }
11933
0
    }
11934
11935
    // For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items)
11936
3.00k
    ImRect scoring_rect;
11937
3.00k
    if (window != NULL)
11938
2.08k
    {
11939
2.08k
        ImRect nav_rect_rel = !window->NavRectRel[g.NavLayer].IsInverted() ? window->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0);
11940
2.08k
        scoring_rect = WindowRectRelToAbs(window, nav_rect_rel);
11941
2.08k
        scoring_rect.TranslateY(scoring_rect_offset_y);
11942
2.08k
        scoring_rect.Min.x = ImMin(scoring_rect.Min.x + 1.0f, scoring_rect.Max.x);
11943
2.08k
        scoring_rect.Max.x = scoring_rect.Min.x;
11944
2.08k
        IM_ASSERT(!scoring_rect.IsInverted()); // Ensure if we have a finite, non-inverted bounding box here will allow us to remove extraneous ImFabs() calls in NavScoreItem().
11945
        //GetForegroundDrawList()->AddRect(scoring_rect.Min, scoring_rect.Max, IM_COL32(255,200,0,255)); // [DEBUG]
11946
        //if (!g.NavScoringNoClipRect.IsInverted()) { GetForegroundDrawList()->AddRect(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(255, 200, 0, 255)); } // [DEBUG]
11947
2.08k
    }
11948
3.00k
    g.NavScoringRect = scoring_rect;
11949
3.00k
    g.NavScoringNoClipRect.Add(scoring_rect);
11950
3.00k
}
11951
11952
void ImGui::NavUpdateCreateTabbingRequest()
11953
2.95k
{
11954
2.95k
    ImGuiContext& g = *GImGui;
11955
2.95k
    ImGuiWindow* window = g.NavWindow;
11956
2.95k
    IM_ASSERT(g.NavMoveDir == ImGuiDir_None);
11957
2.95k
    if (window == NULL || g.NavWindowingTarget != NULL || (window->Flags & ImGuiWindowFlags_NoNavInputs))
11958
914
        return;
11959
11960
2.04k
    const bool tab_pressed = IsKeyPressed(ImGuiKey_Tab, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat) && !g.IO.KeyCtrl && !g.IO.KeyAlt;
11961
2.04k
    if (!tab_pressed)
11962
1.93k
        return;
11963
11964
    // Initiate tabbing request
11965
    // (this is ALWAYS ENABLED, regardless of ImGuiConfigFlags_NavEnableKeyboard flag!)
11966
    // Initially this was designed to use counters and modulo arithmetic, but that could not work with unsubmitted items (list clipper). Instead we use a strategy close to other move requests.
11967
    // See NavProcessItemForTabbingRequest() for a description of the various forward/backward tabbing cases with and without wrapping.
11968
    //// FIXME: We use (g.ActiveId == 0) but (g.NavDisableHighlight == false) might be righter once we can tab through anything
11969
105
    g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.ActiveId == 0) ? 0 : +1;
11970
105
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
11971
105
    ImGuiDir clip_dir = (g.NavTabbingDir < 0) ? ImGuiDir_Up : ImGuiDir_Down;
11972
105
    NavMoveRequestSubmit(ImGuiDir_None, clip_dir, ImGuiNavMoveFlags_Tabbing, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
11973
105
    g.NavTabbingCounter = -1;
11974
105
}
11975
11976
// Apply result from previous frame navigation directional move request. Always called from NavUpdate()
11977
void ImGui::NavMoveRequestApplyResult()
11978
144
{
11979
144
    ImGuiContext& g = *GImGui;
11980
#if IMGUI_DEBUG_NAV_SCORING
11981
    if (g.NavMoveFlags & ImGuiNavMoveFlags_DebugNoResult) // [DEBUG] Scoring all items in NavWindow at all times
11982
        return;
11983
#endif
11984
11985
    // Select which result to use
11986
144
    ImGuiNavItemData* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : (g.NavMoveResultOther.ID != 0) ? &g.NavMoveResultOther : NULL;
11987
11988
    // Tabbing forward wrap
11989
144
    if (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing)
11990
102
        if ((g.NavTabbingCounter == 1 || g.NavTabbingDir == 0) && g.NavTabbingResultFirst.ID)
11991
0
            result = &g.NavTabbingResultFirst;
11992
11993
    // In a situation when there are no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result)
11994
144
    if (result == NULL)
11995
144
    {
11996
144
        if (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing)
11997
102
            g.NavMoveFlags |= ImGuiNavMoveFlags_DontSetNavHighlight;
11998
144
        if (g.NavId != 0 && (g.NavMoveFlags & ImGuiNavMoveFlags_DontSetNavHighlight) == 0)
11999
0
            NavRestoreHighlightAfterMove();
12000
144
        return;
12001
144
    }
12002
12003
    // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
12004
0
    if (g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
12005
0
        if (g.NavMoveResultLocalVisible.ID != 0 && g.NavMoveResultLocalVisible.ID != g.NavId)
12006
0
            result = &g.NavMoveResultLocalVisible;
12007
12008
    // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
12009
0
    if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
12010
0
        if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
12011
0
            result = &g.NavMoveResultOther;
12012
0
    IM_ASSERT(g.NavWindow && result->Window);
12013
12014
    // Scroll to keep newly navigated item fully into view.
12015
0
    if (g.NavLayer == ImGuiNavLayer_Main)
12016
0
    {
12017
0
        if (g.NavMoveFlags & ImGuiNavMoveFlags_ScrollToEdgeY)
12018
0
        {
12019
            // FIXME: Should remove this
12020
0
            float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;
12021
0
            SetScrollY(result->Window, scroll_target);
12022
0
        }
12023
0
        else
12024
0
        {
12025
0
            ImRect rect_abs = WindowRectRelToAbs(result->Window, result->RectRel);
12026
0
            ScrollToRectEx(result->Window, rect_abs, g.NavMoveScrollFlags);
12027
0
        }
12028
0
    }
12029
12030
0
    if (g.NavWindow != result->Window)
12031
0
    {
12032
0
        IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name);
12033
0
        g.NavWindow = result->Window;
12034
0
    }
12035
0
    if (g.ActiveId != result->ID)
12036
0
        ClearActiveID();
12037
0
    if (g.NavId != result->ID)
12038
0
    {
12039
        // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
12040
0
        g.NavJustMovedToId = result->ID;
12041
0
        g.NavJustMovedToFocusScopeId = result->FocusScopeId;
12042
0
        g.NavJustMovedToKeyMods = g.NavMoveKeyMods;
12043
0
    }
12044
12045
    // Focus
12046
0
    IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
12047
0
    SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
12048
12049
    // Tabbing: Activates Inputable or Focus non-Inputable
12050
0
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) && (result->InFlags & ImGuiItemFlags_Inputable))
12051
0
    {
12052
0
        g.NavNextActivateId = result->ID;
12053
0
        g.NavNextActivateFlags = ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState;
12054
0
        g.NavMoveFlags |= ImGuiNavMoveFlags_DontSetNavHighlight;
12055
0
    }
12056
12057
    // Activate
12058
0
    if (g.NavMoveFlags & ImGuiNavMoveFlags_Activate)
12059
0
    {
12060
0
        g.NavNextActivateId = result->ID;
12061
0
        g.NavNextActivateFlags = ImGuiActivateFlags_None;
12062
0
    }
12063
12064
    // Enable nav highlight
12065
0
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_DontSetNavHighlight) == 0)
12066
0
        NavRestoreHighlightAfterMove();
12067
0
}
12068
12069
// Process NavCancel input (to close a popup, get back to parent, clear focus)
12070
// FIXME: In order to support e.g. Escape to clear a selection we'll need:
12071
// - either to store the equivalent of ActiveIdUsingKeyInputMask for a FocusScope and test for it.
12072
// - either to move most/all of those tests to the epilogue/end functions of the scope they are dealing with (e.g. exit child window in EndChild()) or in EndFrame(), to allow an earlier intercept
12073
static void ImGui::NavUpdateCancelRequest()
12074
3.00k
{
12075
3.00k
    ImGuiContext& g = *GImGui;
12076
3.00k
    const bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12077
3.00k
    const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12078
3.00k
    if (!(nav_keyboard_active && IsKeyPressed(ImGuiKey_Escape, ImGuiKeyOwner_None)) && !(nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadCancel, ImGuiKeyOwner_None)))
12079
3.00k
        return;
12080
12081
0
    IMGUI_DEBUG_LOG_NAV("[nav] NavUpdateCancelRequest()\n");
12082
0
    if (g.ActiveId != 0)
12083
0
    {
12084
0
        ClearActiveID();
12085
0
    }
12086
0
    else if (g.NavLayer != ImGuiNavLayer_Main)
12087
0
    {
12088
        // Leave the "menu" layer
12089
0
        NavRestoreLayer(ImGuiNavLayer_Main);
12090
0
        NavRestoreHighlightAfterMove();
12091
0
    }
12092
0
    else if (g.NavWindow && g.NavWindow != g.NavWindow->RootWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->ParentWindow)
12093
0
    {
12094
        // Exit child window
12095
0
        ImGuiWindow* child_window = g.NavWindow;
12096
0
        ImGuiWindow* parent_window = g.NavWindow->ParentWindow;
12097
0
        IM_ASSERT(child_window->ChildId != 0);
12098
0
        ImRect child_rect = child_window->Rect();
12099
0
        FocusWindow(parent_window);
12100
0
        SetNavID(child_window->ChildId, ImGuiNavLayer_Main, 0, WindowRectAbsToRel(parent_window, child_rect));
12101
0
        NavRestoreHighlightAfterMove();
12102
0
    }
12103
0
    else if (g.OpenPopupStack.Size > 0 && g.OpenPopupStack.back().Window != NULL && !(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
12104
0
    {
12105
        // Close open popup/menu
12106
0
        ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
12107
0
    }
12108
0
    else
12109
0
    {
12110
        // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
12111
0
        if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
12112
0
            g.NavWindow->NavLastIds[0] = 0;
12113
0
        g.NavId = 0;
12114
0
    }
12115
0
}
12116
12117
// Handle PageUp/PageDown/Home/End keys
12118
// Called from NavUpdateCreateMoveRequest() which will use our output to create a move request
12119
// FIXME-NAV: This doesn't work properly with NavFlattened siblings as we use NavWindow rectangle for reference
12120
// FIXME-NAV: how to get Home/End to aim at the beginning/end of a 2D grid?
12121
static float ImGui::NavUpdatePageUpPageDown()
12122
2.04k
{
12123
2.04k
    ImGuiContext& g = *GImGui;
12124
2.04k
    ImGuiWindow* window = g.NavWindow;
12125
2.04k
    if ((window->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL)
12126
0
        return 0.0f;
12127
12128
2.04k
    const bool page_up_held = IsKeyDown(ImGuiKey_PageUp, ImGuiKeyOwner_None);
12129
2.04k
    const bool page_down_held = IsKeyDown(ImGuiKey_PageDown, ImGuiKeyOwner_None);
12130
2.04k
    const bool home_pressed = IsKeyPressed(ImGuiKey_Home, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat);
12131
2.04k
    const bool end_pressed = IsKeyPressed(ImGuiKey_End, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat);
12132
2.04k
    if (page_up_held == page_down_held && home_pressed == end_pressed) // Proceed if either (not both) are pressed, otherwise early out
12133
1.96k
        return 0.0f;
12134
12135
83
    if (g.NavLayer != ImGuiNavLayer_Main)
12136
0
        NavRestoreLayer(ImGuiNavLayer_Main);
12137
12138
83
    if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavHasScroll)
12139
83
    {
12140
        // Fallback manual-scroll when window has no navigable item
12141
83
        if (IsKeyPressed(ImGuiKey_PageUp, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat))
12142
23
            SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight());
12143
60
        else if (IsKeyPressed(ImGuiKey_PageDown, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat))
12144
0
            SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight());
12145
60
        else if (home_pressed)
12146
7
            SetScrollY(window, 0.0f);
12147
53
        else if (end_pressed)
12148
0
            SetScrollY(window, window->ScrollMax.y);
12149
83
    }
12150
0
    else
12151
0
    {
12152
0
        ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
12153
0
        const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
12154
0
        float nav_scoring_rect_offset_y = 0.0f;
12155
0
        if (IsKeyPressed(ImGuiKey_PageUp, true))
12156
0
        {
12157
0
            nav_scoring_rect_offset_y = -page_offset_y;
12158
0
            g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset up, we request the down direction (so we can always land on the last item)
12159
0
            g.NavMoveClipDir = ImGuiDir_Up;
12160
0
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
12161
0
        }
12162
0
        else if (IsKeyPressed(ImGuiKey_PageDown, true))
12163
0
        {
12164
0
            nav_scoring_rect_offset_y = +page_offset_y;
12165
0
            g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset down, we request the up direction (so we can always land on the last item)
12166
0
            g.NavMoveClipDir = ImGuiDir_Down;
12167
0
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
12168
0
        }
12169
0
        else if (home_pressed)
12170
0
        {
12171
            // FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
12172
            // Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdgeY flag, we don't scroll immediately to avoid scrolling happening before nav result.
12173
            // Preserve current horizontal position if we have any.
12174
0
            nav_rect_rel.Min.y = nav_rect_rel.Max.y = 0.0f;
12175
0
            if (nav_rect_rel.IsInverted())
12176
0
                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
12177
0
            g.NavMoveDir = ImGuiDir_Down;
12178
0
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
12179
            // FIXME-NAV: MoveClipDir left to _None, intentional?
12180
0
        }
12181
0
        else if (end_pressed)
12182
0
        {
12183
0
            nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ContentSize.y;
12184
0
            if (nav_rect_rel.IsInverted())
12185
0
                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
12186
0
            g.NavMoveDir = ImGuiDir_Up;
12187
0
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
12188
            // FIXME-NAV: MoveClipDir left to _None, intentional?
12189
0
        }
12190
0
        return nav_scoring_rect_offset_y;
12191
0
    }
12192
83
    return 0.0f;
12193
83
}
12194
12195
static void ImGui::NavEndFrame()
12196
3.00k
{
12197
3.00k
    ImGuiContext& g = *GImGui;
12198
12199
    // Show CTRL+TAB list window
12200
3.00k
    if (g.NavWindowingTarget != NULL)
12201
0
        NavUpdateWindowingOverlay();
12202
12203
    // Perform wrap-around in menus
12204
    // FIXME-NAV: Wrap may need to apply a weight bias on the other axis. e.g. 4x4 grid with 2 last items missing on last item won't handle LoopY/WrapY correctly.
12205
    // FIXME-NAV: Wrap (not Loop) support could be handled by the scoring function and then WrapX would function without an extra frame.
12206
3.00k
    const ImGuiNavMoveFlags wanted_flags = ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY;
12207
3.00k
    if (g.NavWindow && NavMoveRequestButNoResultYet() && (g.NavMoveFlags & wanted_flags) && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0)
12208
0
        NavUpdateCreateWrappingRequest();
12209
3.00k
}
12210
12211
static void ImGui::NavUpdateCreateWrappingRequest()
12212
0
{
12213
0
    ImGuiContext& g = *GImGui;
12214
0
    ImGuiWindow* window = g.NavWindow;
12215
12216
0
    bool do_forward = false;
12217
0
    ImRect bb_rel = window->NavRectRel[g.NavLayer];
12218
0
    ImGuiDir clip_dir = g.NavMoveDir;
12219
0
    const ImGuiNavMoveFlags move_flags = g.NavMoveFlags;
12220
0
    if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
12221
0
    {
12222
0
        bb_rel.Min.x = bb_rel.Max.x = window->ContentSize.x + window->WindowPadding.x;
12223
0
        if (move_flags & ImGuiNavMoveFlags_WrapX)
12224
0
        {
12225
0
            bb_rel.TranslateY(-bb_rel.GetHeight()); // Previous row
12226
0
            clip_dir = ImGuiDir_Up;
12227
0
        }
12228
0
        do_forward = true;
12229
0
    }
12230
0
    if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
12231
0
    {
12232
0
        bb_rel.Min.x = bb_rel.Max.x = -window->WindowPadding.x;
12233
0
        if (move_flags & ImGuiNavMoveFlags_WrapX)
12234
0
        {
12235
0
            bb_rel.TranslateY(+bb_rel.GetHeight()); // Next row
12236
0
            clip_dir = ImGuiDir_Down;
12237
0
        }
12238
0
        do_forward = true;
12239
0
    }
12240
0
    if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
12241
0
    {
12242
0
        bb_rel.Min.y = bb_rel.Max.y = window->ContentSize.y + window->WindowPadding.y;
12243
0
        if (move_flags & ImGuiNavMoveFlags_WrapY)
12244
0
        {
12245
0
            bb_rel.TranslateX(-bb_rel.GetWidth()); // Previous column
12246
0
            clip_dir = ImGuiDir_Left;
12247
0
        }
12248
0
        do_forward = true;
12249
0
    }
12250
0
    if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
12251
0
    {
12252
0
        bb_rel.Min.y = bb_rel.Max.y = -window->WindowPadding.y;
12253
0
        if (move_flags & ImGuiNavMoveFlags_WrapY)
12254
0
        {
12255
0
            bb_rel.TranslateX(+bb_rel.GetWidth()); // Next column
12256
0
            clip_dir = ImGuiDir_Right;
12257
0
        }
12258
0
        do_forward = true;
12259
0
    }
12260
0
    if (!do_forward)
12261
0
        return;
12262
0
    window->NavRectRel[g.NavLayer] = bb_rel;
12263
0
    NavMoveRequestForward(g.NavMoveDir, clip_dir, move_flags, g.NavMoveScrollFlags);
12264
0
}
12265
12266
static int ImGui::FindWindowFocusIndex(ImGuiWindow* window)
12267
0
{
12268
0
    ImGuiContext& g = *GImGui;
12269
0
    IM_UNUSED(g);
12270
0
    int order = window->FocusOrder;
12271
0
    IM_ASSERT(window->RootWindow == window); // No child window (not testing _ChildWindow because of docking)
12272
0
    IM_ASSERT(g.WindowsFocusOrder[order] == window);
12273
0
    return order;
12274
0
}
12275
12276
static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
12277
0
{
12278
0
    ImGuiContext& g = *GImGui;
12279
0
    for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
12280
0
        if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))
12281
0
            return g.WindowsFocusOrder[i];
12282
0
    return NULL;
12283
0
}
12284
12285
static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
12286
0
{
12287
0
    ImGuiContext& g = *GImGui;
12288
0
    IM_ASSERT(g.NavWindowingTarget);
12289
0
    if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
12290
0
        return;
12291
12292
0
    const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget);
12293
0
    ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
12294
0
    if (!window_target)
12295
0
        window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
12296
0
    if (window_target) // Don't reset windowing target if there's a single window in the list
12297
0
    {
12298
0
        g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
12299
0
        g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
12300
0
    }
12301
0
    g.NavWindowingToggleLayer = false;
12302
0
}
12303
12304
// Windowing management mode
12305
// Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
12306
// Gamepad:  Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
12307
static void ImGui::NavUpdateWindowing()
12308
3.00k
{
12309
3.00k
    ImGuiContext& g = *GImGui;
12310
3.00k
    ImGuiIO& io = g.IO;
12311
12312
3.00k
    ImGuiWindow* apply_focus_window = NULL;
12313
3.00k
    bool apply_toggle_layer = false;
12314
12315
3.00k
    ImGuiWindow* modal_window = GetTopMostPopupModal();
12316
3.00k
    bool allow_windowing = (modal_window == NULL);
12317
3.00k
    if (!allow_windowing)
12318
0
        g.NavWindowingTarget = NULL;
12319
12320
    // Fade out
12321
3.00k
    if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
12322
0
    {
12323
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - io.DeltaTime * 10.0f, 0.0f);
12324
0
        if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
12325
0
            g.NavWindowingTargetAnim = NULL;
12326
0
    }
12327
12328
    // Start CTRL+Tab or Square+L/R window selection
12329
3.00k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12330
3.00k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12331
3.00k
    const bool keyboard_next_window = allow_windowing && g.ConfigNavWindowingKeyNext && Shortcut(g.ConfigNavWindowingKeyNext, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways);
12332
3.00k
    const bool keyboard_prev_window = allow_windowing && g.ConfigNavWindowingKeyPrev && Shortcut(g.ConfigNavWindowingKeyPrev, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways);
12333
3.00k
    const bool start_windowing_with_gamepad = allow_windowing && nav_gamepad_active && !g.NavWindowingTarget && IsKeyPressed(ImGuiKey_NavGamepadMenu, 0, ImGuiInputFlags_None);
12334
3.00k
    const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && (keyboard_next_window || keyboard_prev_window); // Note: enabled even without NavEnableKeyboard!
12335
3.00k
    if (start_windowing_with_gamepad || start_windowing_with_keyboard)
12336
0
        if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
12337
0
        {
12338
0
            g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow;
12339
0
            g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
12340
0
            g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
12341
0
            g.NavWindowingToggleLayer = start_windowing_with_gamepad ? true : false; // Gamepad starts toggling layer
12342
0
            g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad;
12343
0
        }
12344
12345
    // Gamepad update
12346
3.00k
    g.NavWindowingTimer += io.DeltaTime;
12347
3.00k
    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Gamepad)
12348
0
    {
12349
        // Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise
12350
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
12351
12352
        // Select window to focus
12353
0
        const int focus_change_dir = (int)IsKeyPressed(ImGuiKey_GamepadL1) - (int)IsKeyPressed(ImGuiKey_GamepadR1);
12354
0
        if (focus_change_dir != 0)
12355
0
        {
12356
0
            NavUpdateWindowingHighlightWindow(focus_change_dir);
12357
0
            g.NavWindowingHighlightAlpha = 1.0f;
12358
0
        }
12359
12360
        // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
12361
0
        if (!IsKeyDown(ImGuiKey_NavGamepadMenu))
12362
0
        {
12363
0
            g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
12364
0
            if (g.NavWindowingToggleLayer && g.NavWindow)
12365
0
                apply_toggle_layer = true;
12366
0
            else if (!g.NavWindowingToggleLayer)
12367
0
                apply_focus_window = g.NavWindowingTarget;
12368
0
            g.NavWindowingTarget = NULL;
12369
0
        }
12370
0
    }
12371
12372
    // Keyboard: Focus
12373
3.00k
    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Keyboard)
12374
0
    {
12375
        // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
12376
0
        ImGuiKeyChord shared_mods = ((g.ConfigNavWindowingKeyNext ? g.ConfigNavWindowingKeyNext : ImGuiMod_Mask_) & (g.ConfigNavWindowingKeyPrev ? g.ConfigNavWindowingKeyPrev : ImGuiMod_Mask_)) & ImGuiMod_Mask_;
12377
0
        IM_ASSERT(shared_mods != 0); // Next/Prev shortcut currently needs a shared modifier to "hold", otherwise Prev actions would keep cycling between two windows.
12378
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
12379
0
        if (keyboard_next_window || keyboard_prev_window)
12380
0
            NavUpdateWindowingHighlightWindow(keyboard_next_window ? -1 : +1);
12381
0
        else if ((io.KeyMods & shared_mods) != shared_mods)
12382
0
            apply_focus_window = g.NavWindowingTarget;
12383
0
    }
12384
12385
    // Keyboard: Press and Release ALT to toggle menu layer
12386
    // - Testing that only Alt is tested prevents Alt+Shift or AltGR from toggling menu layer.
12387
    // - AltGR is normally Alt+Ctrl but we can't reliably detect it (not all backends/systems/layout emit it as Alt+Ctrl). But even on keyboards without AltGR we don't want Alt+Ctrl to open menu anyway.
12388
3.00k
    if (nav_keyboard_active && IsKeyPressed(ImGuiMod_Alt, ImGuiKeyOwner_None))
12389
0
    {
12390
0
        g.NavWindowingToggleLayer = true;
12391
0
        g.NavInputSource = ImGuiInputSource_Keyboard;
12392
0
    }
12393
3.00k
    if (g.NavWindowingToggleLayer && g.NavInputSource == ImGuiInputSource_Keyboard)
12394
0
    {
12395
        // We cancel toggling nav layer when any text has been typed (generally while holding Alt). (See #370)
12396
        // We cancel toggling nav layer when other modifiers are pressed. (See #4439)
12397
        // We cancel toggling nav layer if an owner has claimed the key.
12398
0
        if (io.InputQueueCharacters.Size > 0 || io.KeyCtrl || io.KeyShift || io.KeySuper || TestKeyOwner(ImGuiMod_Alt, ImGuiKeyOwner_None) == false)
12399
0
            g.NavWindowingToggleLayer = false;
12400
12401
        // Apply layer toggle on release
12402
        // Important: as before version <18314 we lacked an explicit IO event for focus gain/loss, we also compare mouse validity to detect old backends clearing mouse pos on focus loss.
12403
0
        if (IsKeyReleased(ImGuiMod_Alt) && g.NavWindowingToggleLayer)
12404
0
            if (g.ActiveId == 0 || g.ActiveIdAllowOverlap)
12405
0
                if (IsMousePosValid(&io.MousePos) == IsMousePosValid(&io.MousePosPrev))
12406
0
                    apply_toggle_layer = true;
12407
0
        if (!IsKeyDown(ImGuiMod_Alt))
12408
0
            g.NavWindowingToggleLayer = false;
12409
0
    }
12410
12411
    // Move window
12412
3.00k
    if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
12413
0
    {
12414
0
        ImVec2 nav_move_dir;
12415
0
        if (g.NavInputSource == ImGuiInputSource_Keyboard && !io.KeyShift)
12416
0
            nav_move_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
12417
0
        if (g.NavInputSource == ImGuiInputSource_Gamepad)
12418
0
            nav_move_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
12419
0
        if (nav_move_dir.x != 0.0f || nav_move_dir.y != 0.0f)
12420
0
        {
12421
0
            const float NAV_MOVE_SPEED = 800.0f;
12422
0
            const float move_step = NAV_MOVE_SPEED * io.DeltaTime * ImMin(io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y);
12423
0
            g.NavWindowingAccumDeltaPos += nav_move_dir * move_step;
12424
0
            g.NavDisableMouseHover = true;
12425
0
            ImVec2 accum_floored = ImFloor(g.NavWindowingAccumDeltaPos);
12426
0
            if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
12427
0
            {
12428
0
                ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindowDockTree;
12429
0
                SetWindowPos(moving_window, moving_window->Pos + accum_floored, ImGuiCond_Always);
12430
0
                g.NavWindowingAccumDeltaPos -= accum_floored;
12431
0
            }
12432
0
        }
12433
0
    }
12434
12435
    // Apply final focus
12436
3.00k
    if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))
12437
0
    {
12438
0
        ImGuiViewport* previous_viewport = g.NavWindow ? g.NavWindow->Viewport : NULL;
12439
0
        ClearActiveID();
12440
0
        NavRestoreHighlightAfterMove();
12441
0
        apply_focus_window = NavRestoreLastChildNavWindow(apply_focus_window);
12442
0
        ClosePopupsOverWindow(apply_focus_window, false);
12443
0
        FocusWindow(apply_focus_window);
12444
0
        if (apply_focus_window->NavLastIds[0] == 0)
12445
0
            NavInitWindow(apply_focus_window, false);
12446
12447
        // If the window has ONLY a menu layer (no main layer), select it directly
12448
        // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame,
12449
        // so CTRL+Tab where the keys are only held for 1 frame will be able to use correct layers mask since
12450
        // the target window as already been previewed once.
12451
        // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases,
12452
        // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask*
12453
        // won't be valid.
12454
0
        if (apply_focus_window->DC.NavLayersActiveMaskNext == (1 << ImGuiNavLayer_Menu))
12455
0
            g.NavLayer = ImGuiNavLayer_Menu;
12456
12457
        // Request OS level focus
12458
0
        if (apply_focus_window->Viewport != previous_viewport && g.PlatformIO.Platform_SetWindowFocus)
12459
0
            g.PlatformIO.Platform_SetWindowFocus(apply_focus_window->Viewport);
12460
0
    }
12461
3.00k
    if (apply_focus_window)
12462
0
        g.NavWindowingTarget = NULL;
12463
12464
    // Apply menu/layer toggle
12465
3.00k
    if (apply_toggle_layer && g.NavWindow)
12466
0
    {
12467
0
        ClearActiveID();
12468
12469
        // Move to parent menu if necessary
12470
0
        ImGuiWindow* new_nav_window = g.NavWindow;
12471
0
        while (new_nav_window->ParentWindow
12472
0
            && (new_nav_window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0
12473
0
            && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
12474
0
            && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
12475
0
            new_nav_window = new_nav_window->ParentWindow;
12476
0
        if (new_nav_window != g.NavWindow)
12477
0
        {
12478
0
            ImGuiWindow* old_nav_window = g.NavWindow;
12479
0
            FocusWindow(new_nav_window);
12480
0
            new_nav_window->NavLastChildNavWindow = old_nav_window;
12481
0
        }
12482
12483
        // Toggle layer
12484
0
        const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
12485
0
        if (new_nav_layer != g.NavLayer)
12486
0
        {
12487
            // Reinitialize navigation when entering menu bar with the Alt key (FIXME: could be a properly of the layer?)
12488
0
            const bool preserve_layer_1_nav_id = (new_nav_window->DockNodeAsHost != NULL);
12489
0
            if (new_nav_layer == ImGuiNavLayer_Menu && !preserve_layer_1_nav_id)
12490
0
                g.NavWindow->NavLastIds[new_nav_layer] = 0;
12491
0
            NavRestoreLayer(new_nav_layer);
12492
0
            NavRestoreHighlightAfterMove();
12493
0
        }
12494
0
    }
12495
3.00k
}
12496
12497
// Window has already passed the IsWindowNavFocusable()
12498
static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
12499
0
{
12500
0
    if (window->Flags & ImGuiWindowFlags_Popup)
12501
0
        return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingPopup);
12502
0
    if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0)
12503
0
        return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingMainMenuBar);
12504
0
    if (window->DockNodeAsHost)
12505
0
        return "(Dock node)"; // Not normally shown to user.
12506
0
    return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingUntitled);
12507
0
}
12508
12509
// Overlay displayed when using CTRL+TAB. Called by EndFrame().
12510
void ImGui::NavUpdateWindowingOverlay()
12511
0
{
12512
0
    ImGuiContext& g = *GImGui;
12513
0
    IM_ASSERT(g.NavWindowingTarget != NULL);
12514
12515
0
    if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
12516
0
        return;
12517
12518
0
    if (g.NavWindowingListWindow == NULL)
12519
0
        g.NavWindowingListWindow = FindWindowByName("###NavWindowingList");
12520
0
    const ImGuiViewport* viewport = /*g.NavWindow ? g.NavWindow->Viewport :*/ GetMainViewport();
12521
0
    SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
12522
0
    SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
12523
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
12524
0
    Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
12525
0
    for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
12526
0
    {
12527
0
        ImGuiWindow* window = g.WindowsFocusOrder[n];
12528
0
        IM_ASSERT(window != NULL); // Fix static analyzers
12529
0
        if (!IsWindowNavFocusable(window))
12530
0
            continue;
12531
0
        const char* label = window->Name;
12532
0
        if (label == FindRenderedTextEnd(label))
12533
0
            label = GetFallbackWindowNameForWindowingList(window);
12534
0
        Selectable(label, g.NavWindowingTarget == window);
12535
0
    }
12536
0
    End();
12537
0
    PopStyleVar();
12538
0
}
12539
12540
12541
//-----------------------------------------------------------------------------
12542
// [SECTION] DRAG AND DROP
12543
//-----------------------------------------------------------------------------
12544
12545
bool ImGui::IsDragDropActive()
12546
0
{
12547
0
    ImGuiContext& g = *GImGui;
12548
0
    return g.DragDropActive;
12549
0
}
12550
12551
void ImGui::ClearDragDrop()
12552
0
{
12553
0
    ImGuiContext& g = *GImGui;
12554
0
    g.DragDropActive = false;
12555
0
    g.DragDropPayload.Clear();
12556
0
    g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
12557
0
    g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
12558
0
    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
12559
0
    g.DragDropAcceptFrameCount = -1;
12560
12561
0
    g.DragDropPayloadBufHeap.clear();
12562
0
    memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
12563
0
}
12564
12565
// When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
12566
// If the item has an identifier:
12567
// - This assume/require the item to be activated (typically via ButtonBehavior).
12568
// - Therefore if you want to use this with a mouse button other than left mouse button, it is up to the item itself to activate with another button.
12569
// - We then pull and use the mouse button that was used to activate the item and use it to carry on the drag.
12570
// If the item has no identifier:
12571
// - Currently always assume left mouse button.
12572
bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
12573
0
{
12574
0
    ImGuiContext& g = *GImGui;
12575
0
    ImGuiWindow* window = g.CurrentWindow;
12576
12577
    // FIXME-DRAGDROP: While in the common-most "drag from non-zero active id" case we can tell the mouse button,
12578
    // in both SourceExtern and id==0 cases we may requires something else (explicit flags or some heuristic).
12579
0
    ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
12580
12581
0
    bool source_drag_active = false;
12582
0
    ImGuiID source_id = 0;
12583
0
    ImGuiID source_parent_id = 0;
12584
0
    if (!(flags & ImGuiDragDropFlags_SourceExtern))
12585
0
    {
12586
0
        source_id = g.LastItemData.ID;
12587
0
        if (source_id != 0)
12588
0
        {
12589
            // Common path: items with ID
12590
0
            if (g.ActiveId != source_id)
12591
0
                return false;
12592
0
            if (g.ActiveIdMouseButton != -1)
12593
0
                mouse_button = g.ActiveIdMouseButton;
12594
0
            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
12595
0
                return false;
12596
0
            g.ActiveIdAllowOverlap = false;
12597
0
        }
12598
0
        else
12599
0
        {
12600
            // Uncommon path: items without ID
12601
0
            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
12602
0
                return false;
12603
0
            if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
12604
0
                return false;
12605
12606
            // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
12607
            // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag.
12608
0
            if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
12609
0
            {
12610
0
                IM_ASSERT(0);
12611
0
                return false;
12612
0
            }
12613
12614
            // Magic fallback to handle items with no assigned ID, e.g. Text(), Image()
12615
            // We build a throwaway ID based on current ID stack + relative AABB of items in window.
12616
            // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING/RESIZINGG OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
12617
            // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
12618
            // Rely on keeping other window->LastItemXXX fields intact.
12619
0
            source_id = g.LastItemData.ID = window->GetIDFromRectangle(g.LastItemData.Rect);
12620
0
            KeepAliveID(source_id);
12621
0
            bool is_hovered = ItemHoverable(g.LastItemData.Rect, source_id);
12622
0
            if (is_hovered && g.IO.MouseClicked[mouse_button])
12623
0
            {
12624
0
                SetActiveID(source_id, window);
12625
0
                FocusWindow(window);
12626
0
            }
12627
0
            if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
12628
0
                g.ActiveIdAllowOverlap = is_hovered;
12629
0
        }
12630
0
        if (g.ActiveId != source_id)
12631
0
            return false;
12632
0
        source_parent_id = window->IDStack.back();
12633
0
        source_drag_active = IsMouseDragging(mouse_button);
12634
12635
        // Disable navigation and key inputs while dragging + cancel existing request if any
12636
0
        SetActiveIdUsingAllKeyboardKeys();
12637
0
    }
12638
0
    else
12639
0
    {
12640
0
        window = NULL;
12641
0
        source_id = ImHashStr("#SourceExtern");
12642
0
        source_drag_active = true;
12643
0
    }
12644
12645
0
    if (source_drag_active)
12646
0
    {
12647
0
        if (!g.DragDropActive)
12648
0
        {
12649
0
            IM_ASSERT(source_id != 0);
12650
0
            ClearDragDrop();
12651
0
            ImGuiPayload& payload = g.DragDropPayload;
12652
0
            payload.SourceId = source_id;
12653
0
            payload.SourceParentId = source_parent_id;
12654
0
            g.DragDropActive = true;
12655
0
            g.DragDropSourceFlags = flags;
12656
0
            g.DragDropMouseButton = mouse_button;
12657
0
            if (payload.SourceId == g.ActiveId)
12658
0
                g.ActiveIdNoClearOnFocusLoss = true;
12659
0
        }
12660
0
        g.DragDropSourceFrameCount = g.FrameCount;
12661
0
        g.DragDropWithinSource = true;
12662
12663
0
        if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
12664
0
        {
12665
            // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
12666
            // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
12667
0
            BeginTooltip();
12668
0
            if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
12669
0
            {
12670
0
                ImGuiWindow* tooltip_window = g.CurrentWindow;
12671
0
                tooltip_window->Hidden = tooltip_window->SkipItems = true;
12672
0
                tooltip_window->HiddenFramesCanSkipItems = 1;
12673
0
            }
12674
0
        }
12675
12676
0
        if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
12677
0
            g.LastItemData.StatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
12678
12679
0
        return true;
12680
0
    }
12681
0
    return false;
12682
0
}
12683
12684
void ImGui::EndDragDropSource()
12685
0
{
12686
0
    ImGuiContext& g = *GImGui;
12687
0
    IM_ASSERT(g.DragDropActive);
12688
0
    IM_ASSERT(g.DragDropWithinSource && "Not after a BeginDragDropSource()?");
12689
12690
0
    if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
12691
0
        EndTooltip();
12692
12693
    // Discard the drag if have not called SetDragDropPayload()
12694
0
    if (g.DragDropPayload.DataFrameCount == -1)
12695
0
        ClearDragDrop();
12696
0
    g.DragDropWithinSource = false;
12697
0
}
12698
12699
// Use 'cond' to choose to submit payload on drag start or every frame
12700
bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
12701
0
{
12702
0
    ImGuiContext& g = *GImGui;
12703
0
    ImGuiPayload& payload = g.DragDropPayload;
12704
0
    if (cond == 0)
12705
0
        cond = ImGuiCond_Always;
12706
12707
0
    IM_ASSERT(type != NULL);
12708
0
    IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
12709
0
    IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
12710
0
    IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
12711
0
    IM_ASSERT(payload.SourceId != 0);                               // Not called between BeginDragDropSource() and EndDragDropSource()
12712
12713
0
    if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
12714
0
    {
12715
        // Copy payload
12716
0
        ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
12717
0
        g.DragDropPayloadBufHeap.resize(0);
12718
0
        if (data_size > sizeof(g.DragDropPayloadBufLocal))
12719
0
        {
12720
            // Store in heap
12721
0
            g.DragDropPayloadBufHeap.resize((int)data_size);
12722
0
            payload.Data = g.DragDropPayloadBufHeap.Data;
12723
0
            memcpy(payload.Data, data, data_size);
12724
0
        }
12725
0
        else if (data_size > 0)
12726
0
        {
12727
            // Store locally
12728
0
            memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
12729
0
            payload.Data = g.DragDropPayloadBufLocal;
12730
0
            memcpy(payload.Data, data, data_size);
12731
0
        }
12732
0
        else
12733
0
        {
12734
0
            payload.Data = NULL;
12735
0
        }
12736
0
        payload.DataSize = (int)data_size;
12737
0
    }
12738
0
    payload.DataFrameCount = g.FrameCount;
12739
12740
    // Return whether the payload has been accepted
12741
0
    return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
12742
0
}
12743
12744
bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
12745
0
{
12746
0
    ImGuiContext& g = *GImGui;
12747
0
    if (!g.DragDropActive)
12748
0
        return false;
12749
12750
0
    ImGuiWindow* window = g.CurrentWindow;
12751
0
    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
12752
0
    if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree)
12753
0
        return false;
12754
0
    IM_ASSERT(id != 0);
12755
0
    if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
12756
0
        return false;
12757
0
    if (window->SkipItems)
12758
0
        return false;
12759
12760
0
    IM_ASSERT(g.DragDropWithinTarget == false);
12761
0
    g.DragDropTargetRect = bb;
12762
0
    g.DragDropTargetId = id;
12763
0
    g.DragDropWithinTarget = true;
12764
0
    return true;
12765
0
}
12766
12767
// We don't use BeginDragDropTargetCustom() and duplicate its code because:
12768
// 1) we use LastItemRectHoveredRect which handles items that push a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them.
12769
// 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
12770
// Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
12771
bool ImGui::BeginDragDropTarget()
12772
0
{
12773
0
    ImGuiContext& g = *GImGui;
12774
0
    if (!g.DragDropActive)
12775
0
        return false;
12776
12777
0
    ImGuiWindow* window = g.CurrentWindow;
12778
0
    if (!(g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect))
12779
0
        return false;
12780
0
    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
12781
0
    if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree || window->SkipItems)
12782
0
        return false;
12783
12784
0
    const ImRect& display_rect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? g.LastItemData.DisplayRect : g.LastItemData.Rect;
12785
0
    ImGuiID id = g.LastItemData.ID;
12786
0
    if (id == 0)
12787
0
    {
12788
0
        id = window->GetIDFromRectangle(display_rect);
12789
0
        KeepAliveID(id);
12790
0
    }
12791
0
    if (g.DragDropPayload.SourceId == id)
12792
0
        return false;
12793
12794
0
    IM_ASSERT(g.DragDropWithinTarget == false);
12795
0
    g.DragDropTargetRect = display_rect;
12796
0
    g.DragDropTargetId = id;
12797
0
    g.DragDropWithinTarget = true;
12798
0
    return true;
12799
0
}
12800
12801
bool ImGui::IsDragDropPayloadBeingAccepted()
12802
0
{
12803
0
    ImGuiContext& g = *GImGui;
12804
0
    return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
12805
0
}
12806
12807
const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
12808
0
{
12809
0
    ImGuiContext& g = *GImGui;
12810
0
    ImGuiWindow* window = g.CurrentWindow;
12811
0
    ImGuiPayload& payload = g.DragDropPayload;
12812
0
    IM_ASSERT(g.DragDropActive);                        // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
12813
0
    IM_ASSERT(payload.DataFrameCount != -1);            // Forgot to call EndDragDropTarget() ?
12814
0
    if (type != NULL && !payload.IsDataType(type))
12815
0
        return NULL;
12816
12817
    // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
12818
    // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
12819
0
    const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
12820
0
    ImRect r = g.DragDropTargetRect;
12821
0
    float r_surface = r.GetWidth() * r.GetHeight();
12822
0
    if (r_surface <= g.DragDropAcceptIdCurrRectSurface)
12823
0
    {
12824
0
        g.DragDropAcceptFlags = flags;
12825
0
        g.DragDropAcceptIdCurr = g.DragDropTargetId;
12826
0
        g.DragDropAcceptIdCurrRectSurface = r_surface;
12827
0
    }
12828
12829
    // Render default drop visuals
12830
0
    payload.Preview = was_accepted_previously;
12831
0
    flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that live for 1 frame)
12832
0
    if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
12833
0
        window->DrawList->AddRect(r.Min - ImVec2(3.5f,3.5f), r.Max + ImVec2(3.5f, 3.5f), GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f);
12834
12835
0
    g.DragDropAcceptFrameCount = g.FrameCount;
12836
0
    payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting os window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased()
12837
0
    if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
12838
0
        return NULL;
12839
12840
0
    return &payload;
12841
0
}
12842
12843
// FIXME-DRAGDROP: Settle on a proper default visuals for drop target.
12844
void ImGui::RenderDragDropTargetRect(const ImRect& bb)
12845
0
{
12846
0
    GetWindowDrawList()->AddRect(bb.Min - ImVec2(3.5f, 3.5f), bb.Max + ImVec2(3.5f, 3.5f), GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f);
12847
0
}
12848
12849
const ImGuiPayload* ImGui::GetDragDropPayload()
12850
0
{
12851
0
    ImGuiContext& g = *GImGui;
12852
0
    return (g.DragDropActive && g.DragDropPayload.DataFrameCount != -1) ? &g.DragDropPayload : NULL;
12853
0
}
12854
12855
// We don't really use/need this now, but added it for the sake of consistency and because we might need it later.
12856
void ImGui::EndDragDropTarget()
12857
0
{
12858
0
    ImGuiContext& g = *GImGui;
12859
0
    IM_ASSERT(g.DragDropActive);
12860
0
    IM_ASSERT(g.DragDropWithinTarget);
12861
0
    g.DragDropWithinTarget = false;
12862
0
}
12863
12864
//-----------------------------------------------------------------------------
12865
// [SECTION] LOGGING/CAPTURING
12866
//-----------------------------------------------------------------------------
12867
// All text output from the interface can be captured into tty/file/clipboard.
12868
// By default, tree nodes are automatically opened during logging.
12869
//-----------------------------------------------------------------------------
12870
12871
// Pass text data straight to log (without being displayed)
12872
static inline void LogTextV(ImGuiContext& g, const char* fmt, va_list args)
12873
0
{
12874
0
    if (g.LogFile)
12875
0
    {
12876
0
        g.LogBuffer.Buf.resize(0);
12877
0
        g.LogBuffer.appendfv(fmt, args);
12878
0
        ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile);
12879
0
    }
12880
0
    else
12881
0
    {
12882
0
        g.LogBuffer.appendfv(fmt, args);
12883
0
    }
12884
0
}
12885
12886
void ImGui::LogText(const char* fmt, ...)
12887
0
{
12888
0
    ImGuiContext& g = *GImGui;
12889
0
    if (!g.LogEnabled)
12890
0
        return;
12891
12892
0
    va_list args;
12893
0
    va_start(args, fmt);
12894
0
    LogTextV(g, fmt, args);
12895
0
    va_end(args);
12896
0
}
12897
12898
void ImGui::LogTextV(const char* fmt, va_list args)
12899
0
{
12900
0
    ImGuiContext& g = *GImGui;
12901
0
    if (!g.LogEnabled)
12902
0
        return;
12903
12904
0
    LogTextV(g, fmt, args);
12905
0
}
12906
12907
// Internal version that takes a position to decide on newline placement and pad items according to their depth.
12908
// We split text into individual lines to add current tree level padding
12909
// FIXME: This code is a little complicated perhaps, considering simplifying the whole system.
12910
void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
12911
0
{
12912
0
    ImGuiContext& g = *GImGui;
12913
0
    ImGuiWindow* window = g.CurrentWindow;
12914
12915
0
    const char* prefix = g.LogNextPrefix;
12916
0
    const char* suffix = g.LogNextSuffix;
12917
0
    g.LogNextPrefix = g.LogNextSuffix = NULL;
12918
12919
0
    if (!text_end)
12920
0
        text_end = FindRenderedTextEnd(text, text_end);
12921
12922
0
    const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + g.Style.FramePadding.y + 1);
12923
0
    if (ref_pos)
12924
0
        g.LogLinePosY = ref_pos->y;
12925
0
    if (log_new_line)
12926
0
    {
12927
0
        LogText(IM_NEWLINE);
12928
0
        g.LogLineFirstItem = true;
12929
0
    }
12930
12931
0
    if (prefix)
12932
0
        LogRenderedText(ref_pos, prefix, prefix + strlen(prefix)); // Calculate end ourself to ensure "##" are included here.
12933
12934
    // Re-adjust padding if we have popped out of our starting depth
12935
0
    if (g.LogDepthRef > window->DC.TreeDepth)
12936
0
        g.LogDepthRef = window->DC.TreeDepth;
12937
0
    const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
12938
12939
0
    const char* text_remaining = text;
12940
0
    for (;;)
12941
0
    {
12942
        // Split the string. Each new line (after a '\n') is followed by indentation corresponding to the current depth of our log entry.
12943
        // We don't add a trailing \n yet to allow a subsequent item on the same line to be captured.
12944
0
        const char* line_start = text_remaining;
12945
0
        const char* line_end = ImStreolRange(line_start, text_end);
12946
0
        const bool is_last_line = (line_end == text_end);
12947
0
        if (line_start != line_end || !is_last_line)
12948
0
        {
12949
0
            const int line_length = (int)(line_end - line_start);
12950
0
            const int indentation = g.LogLineFirstItem ? tree_depth * 4 : 1;
12951
0
            LogText("%*s%.*s", indentation, "", line_length, line_start);
12952
0
            g.LogLineFirstItem = false;
12953
0
            if (*line_end == '\n')
12954
0
            {
12955
0
                LogText(IM_NEWLINE);
12956
0
                g.LogLineFirstItem = true;
12957
0
            }
12958
0
        }
12959
0
        if (is_last_line)
12960
0
            break;
12961
0
        text_remaining = line_end + 1;
12962
0
    }
12963
12964
0
    if (suffix)
12965
0
        LogRenderedText(ref_pos, suffix, suffix + strlen(suffix));
12966
0
}
12967
12968
// Start logging/capturing text output
12969
void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth)
12970
0
{
12971
0
    ImGuiContext& g = *GImGui;
12972
0
    ImGuiWindow* window = g.CurrentWindow;
12973
0
    IM_ASSERT(g.LogEnabled == false);
12974
0
    IM_ASSERT(g.LogFile == NULL);
12975
0
    IM_ASSERT(g.LogBuffer.empty());
12976
0
    g.LogEnabled = true;
12977
0
    g.LogType = type;
12978
0
    g.LogNextPrefix = g.LogNextSuffix = NULL;
12979
0
    g.LogDepthRef = window->DC.TreeDepth;
12980
0
    g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
12981
0
    g.LogLinePosY = FLT_MAX;
12982
0
    g.LogLineFirstItem = true;
12983
0
}
12984
12985
// Important: doesn't copy underlying data, use carefully (prefix/suffix must be in scope at the time of the next LogRenderedText)
12986
void ImGui::LogSetNextTextDecoration(const char* prefix, const char* suffix)
12987
0
{
12988
0
    ImGuiContext& g = *GImGui;
12989
0
    g.LogNextPrefix = prefix;
12990
0
    g.LogNextSuffix = suffix;
12991
0
}
12992
12993
void ImGui::LogToTTY(int auto_open_depth)
12994
0
{
12995
0
    ImGuiContext& g = *GImGui;
12996
0
    if (g.LogEnabled)
12997
0
        return;
12998
0
    IM_UNUSED(auto_open_depth);
12999
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
13000
0
    LogBegin(ImGuiLogType_TTY, auto_open_depth);
13001
0
    g.LogFile = stdout;
13002
0
#endif
13003
0
}
13004
13005
// Start logging/capturing text output to given file
13006
void ImGui::LogToFile(int auto_open_depth, const char* filename)
13007
0
{
13008
0
    ImGuiContext& g = *GImGui;
13009
0
    if (g.LogEnabled)
13010
0
        return;
13011
13012
    // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
13013
    // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
13014
    // By opening the file in binary mode "ab" we have consistent output everywhere.
13015
0
    if (!filename)
13016
0
        filename = g.IO.LogFilename;
13017
0
    if (!filename || !filename[0])
13018
0
        return;
13019
0
    ImFileHandle f = ImFileOpen(filename, "ab");
13020
0
    if (!f)
13021
0
    {
13022
0
        IM_ASSERT(0);
13023
0
        return;
13024
0
    }
13025
13026
0
    LogBegin(ImGuiLogType_File, auto_open_depth);
13027
0
    g.LogFile = f;
13028
0
}
13029
13030
// Start logging/capturing text output to clipboard
13031
void ImGui::LogToClipboard(int auto_open_depth)
13032
0
{
13033
0
    ImGuiContext& g = *GImGui;
13034
0
    if (g.LogEnabled)
13035
0
        return;
13036
0
    LogBegin(ImGuiLogType_Clipboard, auto_open_depth);
13037
0
}
13038
13039
void ImGui::LogToBuffer(int auto_open_depth)
13040
0
{
13041
0
    ImGuiContext& g = *GImGui;
13042
0
    if (g.LogEnabled)
13043
0
        return;
13044
0
    LogBegin(ImGuiLogType_Buffer, auto_open_depth);
13045
0
}
13046
13047
void ImGui::LogFinish()
13048
6.00k
{
13049
6.00k
    ImGuiContext& g = *GImGui;
13050
6.00k
    if (!g.LogEnabled)
13051
6.00k
        return;
13052
13053
0
    LogText(IM_NEWLINE);
13054
0
    switch (g.LogType)
13055
0
    {
13056
0
    case ImGuiLogType_TTY:
13057
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
13058
0
        fflush(g.LogFile);
13059
0
#endif
13060
0
        break;
13061
0
    case ImGuiLogType_File:
13062
0
        ImFileClose(g.LogFile);
13063
0
        break;
13064
0
    case ImGuiLogType_Buffer:
13065
0
        break;
13066
0
    case ImGuiLogType_Clipboard:
13067
0
        if (!g.LogBuffer.empty())
13068
0
            SetClipboardText(g.LogBuffer.begin());
13069
0
        break;
13070
0
    case ImGuiLogType_None:
13071
0
        IM_ASSERT(0);
13072
0
        break;
13073
0
    }
13074
13075
0
    g.LogEnabled = false;
13076
0
    g.LogType = ImGuiLogType_None;
13077
0
    g.LogFile = NULL;
13078
0
    g.LogBuffer.clear();
13079
0
}
13080
13081
// Helper to display logging buttons
13082
// FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
13083
void ImGui::LogButtons()
13084
0
{
13085
0
    ImGuiContext& g = *GImGui;
13086
13087
0
    PushID("LogButtons");
13088
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
13089
0
    const bool log_to_tty = Button("Log To TTY"); SameLine();
13090
#else
13091
    const bool log_to_tty = false;
13092
#endif
13093
0
    const bool log_to_file = Button("Log To File"); SameLine();
13094
0
    const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
13095
0
    PushAllowKeyboardFocus(false);
13096
0
    SetNextItemWidth(80.0f);
13097
0
    SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL);
13098
0
    PopAllowKeyboardFocus();
13099
0
    PopID();
13100
13101
    // Start logging at the end of the function so that the buttons don't appear in the log
13102
0
    if (log_to_tty)
13103
0
        LogToTTY();
13104
0
    if (log_to_file)
13105
0
        LogToFile();
13106
0
    if (log_to_clipboard)
13107
0
        LogToClipboard();
13108
0
}
13109
13110
13111
//-----------------------------------------------------------------------------
13112
// [SECTION] SETTINGS
13113
//-----------------------------------------------------------------------------
13114
// - UpdateSettings() [Internal]
13115
// - MarkIniSettingsDirty() [Internal]
13116
// - CreateNewWindowSettings() [Internal]
13117
// - FindWindowSettings() [Internal]
13118
// - FindOrCreateWindowSettings() [Internal]
13119
// - FindSettingsHandler() [Internal]
13120
// - ClearIniSettings() [Internal]
13121
// - LoadIniSettingsFromDisk()
13122
// - LoadIniSettingsFromMemory()
13123
// - SaveIniSettingsToDisk()
13124
// - SaveIniSettingsToMemory()
13125
// - WindowSettingsHandler_***() [Internal]
13126
//-----------------------------------------------------------------------------
13127
13128
// Called by NewFrame()
13129
void ImGui::UpdateSettings()
13130
3.00k
{
13131
    // Load settings on first frame (if not explicitly loaded manually before)
13132
3.00k
    ImGuiContext& g = *GImGui;
13133
3.00k
    if (!g.SettingsLoaded)
13134
1
    {
13135
1
        IM_ASSERT(g.SettingsWindows.empty());
13136
1
        if (g.IO.IniFilename)
13137
0
            LoadIniSettingsFromDisk(g.IO.IniFilename);
13138
1
        g.SettingsLoaded = true;
13139
1
    }
13140
13141
    // Save settings (with a delay after the last modification, so we don't spam disk too much)
13142
3.00k
    if (g.SettingsDirtyTimer > 0.0f)
13143
300
    {
13144
300
        g.SettingsDirtyTimer -= g.IO.DeltaTime;
13145
300
        if (g.SettingsDirtyTimer <= 0.0f)
13146
1
        {
13147
1
            if (g.IO.IniFilename != NULL)
13148
0
                SaveIniSettingsToDisk(g.IO.IniFilename);
13149
1
            else
13150
1
                g.IO.WantSaveIniSettings = true;  // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
13151
1
            g.SettingsDirtyTimer = 0.0f;
13152
1
        }
13153
300
    }
13154
3.00k
}
13155
13156
void ImGui::MarkIniSettingsDirty()
13157
0
{
13158
0
    ImGuiContext& g = *GImGui;
13159
0
    if (g.SettingsDirtyTimer <= 0.0f)
13160
0
        g.SettingsDirtyTimer = g.IO.IniSavingRate;
13161
0
}
13162
13163
void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
13164
564
{
13165
564
    ImGuiContext& g = *GImGui;
13166
564
    if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
13167
3
        if (g.SettingsDirtyTimer <= 0.0f)
13168
1
            g.SettingsDirtyTimer = g.IO.IniSavingRate;
13169
564
}
13170
13171
ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
13172
0
{
13173
0
    ImGuiContext& g = *GImGui;
13174
13175
0
#if !IMGUI_DEBUG_INI_SETTINGS
13176
    // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
13177
    // Preserve the full string when IMGUI_DEBUG_INI_SETTINGS is set to make .ini inspection easier.
13178
0
    if (const char* p = strstr(name, "###"))
13179
0
        name = p;
13180
0
#endif
13181
0
    const size_t name_len = strlen(name);
13182
13183
    // Allocate chunk
13184
0
    const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
13185
0
    ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size);
13186
0
    IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();
13187
0
    settings->ID = ImHashStr(name, name_len);
13188
0
    memcpy(settings->GetName(), name, name_len + 1);   // Store with zero terminator
13189
13190
0
    return settings;
13191
0
}
13192
13193
ImGuiWindowSettings* ImGui::FindWindowSettings(ImGuiID id)
13194
2
{
13195
2
    ImGuiContext& g = *GImGui;
13196
2
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
13197
0
        if (settings->ID == id)
13198
0
            return settings;
13199
2
    return NULL;
13200
2
}
13201
13202
ImGuiWindowSettings* ImGui::FindOrCreateWindowSettings(const char* name)
13203
0
{
13204
0
    if (ImGuiWindowSettings* settings = FindWindowSettings(ImHashStr(name)))
13205
0
        return settings;
13206
0
    return CreateNewWindowSettings(name);
13207
0
}
13208
13209
void ImGui::AddSettingsHandler(const ImGuiSettingsHandler* handler)
13210
2
{
13211
2
    ImGuiContext& g = *GImGui;
13212
2
    IM_ASSERT(FindSettingsHandler(handler->TypeName) == NULL);
13213
2
    g.SettingsHandlers.push_back(*handler);
13214
2
}
13215
13216
void ImGui::RemoveSettingsHandler(const char* type_name)
13217
0
{
13218
0
    ImGuiContext& g = *GImGui;
13219
0
    if (ImGuiSettingsHandler* handler = FindSettingsHandler(type_name))
13220
0
        g.SettingsHandlers.erase(handler);
13221
0
}
13222
13223
ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
13224
2
{
13225
2
    ImGuiContext& g = *GImGui;
13226
2
    const ImGuiID type_hash = ImHashStr(type_name);
13227
3
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13228
1
        if (g.SettingsHandlers[handler_n].TypeHash == type_hash)
13229
0
            return &g.SettingsHandlers[handler_n];
13230
2
    return NULL;
13231
2
}
13232
13233
void ImGui::ClearIniSettings()
13234
0
{
13235
0
    ImGuiContext& g = *GImGui;
13236
0
    g.SettingsIniData.clear();
13237
0
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13238
0
        if (g.SettingsHandlers[handler_n].ClearAllFn)
13239
0
            g.SettingsHandlers[handler_n].ClearAllFn(&g, &g.SettingsHandlers[handler_n]);
13240
0
}
13241
13242
void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
13243
0
{
13244
0
    size_t file_data_size = 0;
13245
0
    char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
13246
0
    if (!file_data)
13247
0
        return;
13248
0
    if (file_data_size > 0)
13249
0
        LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
13250
0
    IM_FREE(file_data);
13251
0
}
13252
13253
// Zero-tolerance, no error reporting, cheap .ini parsing
13254
void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
13255
0
{
13256
0
    ImGuiContext& g = *GImGui;
13257
0
    IM_ASSERT(g.Initialized);
13258
    //IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()");
13259
    //IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
13260
13261
    // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
13262
    // For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy..
13263
0
    if (ini_size == 0)
13264
0
        ini_size = strlen(ini_data);
13265
0
    g.SettingsIniData.Buf.resize((int)ini_size + 1);
13266
0
    char* const buf = g.SettingsIniData.Buf.Data;
13267
0
    char* const buf_end = buf + ini_size;
13268
0
    memcpy(buf, ini_data, ini_size);
13269
0
    buf_end[0] = 0;
13270
13271
    // Call pre-read handlers
13272
    // Some types will clear their data (e.g. dock information) some types will allow merge/override (window)
13273
0
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13274
0
        if (g.SettingsHandlers[handler_n].ReadInitFn)
13275
0
            g.SettingsHandlers[handler_n].ReadInitFn(&g, &g.SettingsHandlers[handler_n]);
13276
13277
0
    void* entry_data = NULL;
13278
0
    ImGuiSettingsHandler* entry_handler = NULL;
13279
13280
0
    char* line_end = NULL;
13281
0
    for (char* line = buf; line < buf_end; line = line_end + 1)
13282
0
    {
13283
        // Skip new lines markers, then find end of the line
13284
0
        while (*line == '\n' || *line == '\r')
13285
0
            line++;
13286
0
        line_end = line;
13287
0
        while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
13288
0
            line_end++;
13289
0
        line_end[0] = 0;
13290
0
        if (line[0] == ';')
13291
0
            continue;
13292
0
        if (line[0] == '[' && line_end > line && line_end[-1] == ']')
13293
0
        {
13294
            // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
13295
0
            line_end[-1] = 0;
13296
0
            const char* name_end = line_end - 1;
13297
0
            const char* type_start = line + 1;
13298
0
            char* type_end = (char*)(void*)ImStrchrRange(type_start, name_end, ']');
13299
0
            const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
13300
0
            if (!type_end || !name_start)
13301
0
                continue;
13302
0
            *type_end = 0; // Overwrite first ']'
13303
0
            name_start++;  // Skip second '['
13304
0
            entry_handler = FindSettingsHandler(type_start);
13305
0
            entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
13306
0
        }
13307
0
        else if (entry_handler != NULL && entry_data != NULL)
13308
0
        {
13309
            // Let type handler parse the line
13310
0
            entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
13311
0
        }
13312
0
    }
13313
0
    g.SettingsLoaded = true;
13314
13315
    // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary)
13316
0
    memcpy(buf, ini_data, ini_size);
13317
13318
    // Call post-read handlers
13319
0
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13320
0
        if (g.SettingsHandlers[handler_n].ApplyAllFn)
13321
0
            g.SettingsHandlers[handler_n].ApplyAllFn(&g, &g.SettingsHandlers[handler_n]);
13322
0
}
13323
13324
void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
13325
0
{
13326
0
    ImGuiContext& g = *GImGui;
13327
0
    g.SettingsDirtyTimer = 0.0f;
13328
0
    if (!ini_filename)
13329
0
        return;
13330
13331
0
    size_t ini_data_size = 0;
13332
0
    const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
13333
0
    ImFileHandle f = ImFileOpen(ini_filename, "wt");
13334
0
    if (!f)
13335
0
        return;
13336
0
    ImFileWrite(ini_data, sizeof(char), ini_data_size, f);
13337
0
    ImFileClose(f);
13338
0
}
13339
13340
// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
13341
const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
13342
0
{
13343
0
    ImGuiContext& g = *GImGui;
13344
0
    g.SettingsDirtyTimer = 0.0f;
13345
0
    g.SettingsIniData.Buf.resize(0);
13346
0
    g.SettingsIniData.Buf.push_back(0);
13347
0
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13348
0
    {
13349
0
        ImGuiSettingsHandler* handler = &g.SettingsHandlers[handler_n];
13350
0
        handler->WriteAllFn(&g, handler, &g.SettingsIniData);
13351
0
    }
13352
0
    if (out_size)
13353
0
        *out_size = (size_t)g.SettingsIniData.size();
13354
0
    return g.SettingsIniData.c_str();
13355
0
}
13356
13357
static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
13358
0
{
13359
0
    ImGuiContext& g = *ctx;
13360
0
    for (int i = 0; i != g.Windows.Size; i++)
13361
0
        g.Windows[i]->SettingsOffset = -1;
13362
0
    g.SettingsWindows.clear();
13363
0
}
13364
13365
static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
13366
0
{
13367
0
    ImGuiWindowSettings* settings = ImGui::FindOrCreateWindowSettings(name);
13368
0
    ImGuiID id = settings->ID;
13369
0
    *settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry
13370
0
    settings->ID = id;
13371
0
    settings->WantApply = true;
13372
0
    return (void*)settings;
13373
0
}
13374
13375
static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
13376
0
{
13377
0
    ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
13378
0
    int x, y;
13379
0
    int i;
13380
0
    ImU32 u1;
13381
0
    if (sscanf(line, "Pos=%i,%i", &x, &y) == 2)             { settings->Pos = ImVec2ih((short)x, (short)y); }
13382
0
    else if (sscanf(line, "Size=%i,%i", &x, &y) == 2)       { settings->Size = ImVec2ih((short)x, (short)y); }
13383
0
    else if (sscanf(line, "ViewportId=0x%08X", &u1) == 1)   { settings->ViewportId = u1; }
13384
0
    else if (sscanf(line, "ViewportPos=%i,%i", &x, &y) == 2){ settings->ViewportPos = ImVec2ih((short)x, (short)y); }
13385
0
    else if (sscanf(line, "Collapsed=%d", &i) == 1)         { settings->Collapsed = (i != 0); }
13386
0
    else if (sscanf(line, "DockId=0x%X,%d", &u1, &i) == 2)  { settings->DockId = u1; settings->DockOrder = (short)i; }
13387
0
    else if (sscanf(line, "DockId=0x%X", &u1) == 1)         { settings->DockId = u1; settings->DockOrder = -1; }
13388
0
    else if (sscanf(line, "ClassId=0x%X", &u1) == 1)        { settings->ClassId = u1; }
13389
0
}
13390
13391
// Apply to existing windows (if any)
13392
static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
13393
0
{
13394
0
    ImGuiContext& g = *ctx;
13395
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
13396
0
        if (settings->WantApply)
13397
0
        {
13398
0
            if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID))
13399
0
                ApplyWindowSettings(window, settings);
13400
0
            settings->WantApply = false;
13401
0
        }
13402
0
}
13403
13404
static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
13405
0
{
13406
    // Gather data from windows that were active during this session
13407
    // (if a window wasn't opened in this session we preserve its settings)
13408
0
    ImGuiContext& g = *ctx;
13409
0
    for (int i = 0; i != g.Windows.Size; i++)
13410
0
    {
13411
0
        ImGuiWindow* window = g.Windows[i];
13412
0
        if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
13413
0
            continue;
13414
13415
0
        ImGuiWindowSettings* settings = (window->SettingsOffset != -1) ? g.SettingsWindows.ptr_from_offset(window->SettingsOffset) : ImGui::FindWindowSettings(window->ID);
13416
0
        if (!settings)
13417
0
        {
13418
0
            settings = ImGui::CreateNewWindowSettings(window->Name);
13419
0
            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
13420
0
        }
13421
0
        IM_ASSERT(settings->ID == window->ID);
13422
0
        settings->Pos = ImVec2ih(window->Pos - window->ViewportPos);
13423
0
        settings->Size = ImVec2ih(window->SizeFull);
13424
0
        settings->ViewportId = window->ViewportId;
13425
0
        settings->ViewportPos = ImVec2ih(window->ViewportPos);
13426
0
        IM_ASSERT(window->DockNode == NULL || window->DockNode->ID == window->DockId);
13427
0
        settings->DockId = window->DockId;
13428
0
        settings->ClassId = window->WindowClass.ClassId;
13429
0
        settings->DockOrder = window->DockOrder;
13430
0
        settings->Collapsed = window->Collapsed;
13431
0
    }
13432
13433
    // Write to text buffer
13434
0
    buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve
13435
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
13436
0
    {
13437
0
        const char* settings_name = settings->GetName();
13438
0
        buf->appendf("[%s][%s]\n", handler->TypeName, settings_name);
13439
0
        if (settings->ViewportId != 0 && settings->ViewportId != ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
13440
0
        {
13441
0
            buf->appendf("ViewportPos=%d,%d\n", settings->ViewportPos.x, settings->ViewportPos.y);
13442
0
            buf->appendf("ViewportId=0x%08X\n", settings->ViewportId);
13443
0
        }
13444
0
        if (settings->Pos.x != 0 || settings->Pos.y != 0 || settings->ViewportId == ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
13445
0
            buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
13446
0
        if (settings->Size.x != 0 || settings->Size.y != 0)
13447
0
            buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
13448
0
        buf->appendf("Collapsed=%d\n", settings->Collapsed);
13449
0
        if (settings->DockId != 0)
13450
0
        {
13451
            //buf->appendf("TabId=0x%08X\n", ImHashStr("#TAB", 4, settings->ID)); // window->TabId: this is not read back but writing it makes "debugging" the .ini data easier.
13452
0
            if (settings->DockOrder == -1)
13453
0
                buf->appendf("DockId=0x%08X\n", settings->DockId);
13454
0
            else
13455
0
                buf->appendf("DockId=0x%08X,%d\n", settings->DockId, settings->DockOrder);
13456
0
            if (settings->ClassId != 0)
13457
0
                buf->appendf("ClassId=0x%08X\n", settings->ClassId);
13458
0
        }
13459
0
        buf->append("\n");
13460
0
    }
13461
0
}
13462
13463
13464
//-----------------------------------------------------------------------------
13465
// [SECTION] LOCALIZATION
13466
//-----------------------------------------------------------------------------
13467
13468
void ImGui::LocalizeRegisterEntries(const ImGuiLocEntry* entries, int count)
13469
1
{
13470
1
    ImGuiContext& g = *GImGui;
13471
9
    for (int n = 0; n < count; n++)
13472
8
        g.LocalizationTable[entries[n].Key] = entries[n].Text;
13473
1
}
13474
13475
13476
//-----------------------------------------------------------------------------
13477
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
13478
//-----------------------------------------------------------------------------
13479
// - GetMainViewport()
13480
// - FindViewportByID()
13481
// - FindViewportByPlatformHandle()
13482
// - SetCurrentViewport() [Internal]
13483
// - SetWindowViewport() [Internal]
13484
// - GetWindowAlwaysWantOwnViewport() [Internal]
13485
// - UpdateTryMergeWindowIntoHostViewport() [Internal]
13486
// - UpdateTryMergeWindowIntoHostViewports() [Internal]
13487
// - TranslateWindowsInViewport() [Internal]
13488
// - ScaleWindowsInViewport() [Internal]
13489
// - FindHoveredViewportFromPlatformWindowStack() [Internal]
13490
// - UpdateViewportsNewFrame() [Internal]
13491
// - UpdateViewportsEndFrame() [Internal]
13492
// - AddUpdateViewport() [Internal]
13493
// - WindowSelectViewport() [Internal]
13494
// - WindowSyncOwnedViewport() [Internal]
13495
// - UpdatePlatformWindows()
13496
// - RenderPlatformWindowsDefault()
13497
// - FindPlatformMonitorForPos() [Internal]
13498
// - FindPlatformMonitorForRect() [Internal]
13499
// - UpdateViewportPlatformMonitor() [Internal]
13500
// - DestroyPlatformWindow() [Internal]
13501
// - DestroyPlatformWindows()
13502
//-----------------------------------------------------------------------------
13503
13504
ImGuiViewport* ImGui::GetMainViewport()
13505
9.00k
{
13506
9.00k
    ImGuiContext& g = *GImGui;
13507
9.00k
    return g.Viewports[0];
13508
9.00k
}
13509
13510
// FIXME: This leaks access to viewports not listed in PlatformIO.Viewports[]. Problematic? (#4236)
13511
ImGuiViewport* ImGui::FindViewportByID(ImGuiID id)
13512
3.00k
{
13513
3.00k
    ImGuiContext& g = *GImGui;
13514
3.00k
    for (int n = 0; n < g.Viewports.Size; n++)
13515
3.00k
        if (g.Viewports[n]->ID == id)
13516
3.00k
            return g.Viewports[n];
13517
0
    return NULL;
13518
3.00k
}
13519
13520
ImGuiViewport* ImGui::FindViewportByPlatformHandle(void* platform_handle)
13521
0
{
13522
0
    ImGuiContext& g = *GImGui;
13523
0
    for (int i = 0; i != g.Viewports.Size; i++)
13524
0
        if (g.Viewports[i]->PlatformHandle == platform_handle)
13525
0
            return g.Viewports[i];
13526
0
    return NULL;
13527
0
}
13528
13529
void ImGui::SetCurrentViewport(ImGuiWindow* current_window, ImGuiViewportP* viewport)
13530
18.0k
{
13531
18.0k
    ImGuiContext& g = *GImGui;
13532
18.0k
    (void)current_window;
13533
13534
18.0k
    if (viewport)
13535
15.0k
        viewport->LastFrameActive = g.FrameCount;
13536
18.0k
    if (g.CurrentViewport == viewport)
13537
12.0k
        return;
13538
6.00k
    g.CurrentDpiScale = viewport ? viewport->DpiScale : 1.0f;
13539
6.00k
    g.CurrentViewport = viewport;
13540
    //IMGUI_DEBUG_LOG_VIEWPORT("[viewport] SetCurrentViewport changed '%s' 0x%08X\n", current_window ? current_window->Name : NULL, viewport ? viewport->ID : 0);
13541
13542
    // Notify platform layer of viewport changes
13543
    // FIXME-DPI: This is only currently used for experimenting with handling of multiple DPI
13544
6.00k
    if (g.CurrentViewport && g.PlatformIO.Platform_OnChangedViewport)
13545
0
        g.PlatformIO.Platform_OnChangedViewport(g.CurrentViewport);
13546
6.00k
}
13547
13548
void ImGui::SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
13549
9.00k
{
13550
    // Abandon viewport
13551
9.00k
    if (window->ViewportOwned && window->Viewport->Window == window)
13552
0
        window->Viewport->Size = ImVec2(0.0f, 0.0f);
13553
13554
9.00k
    window->Viewport = viewport;
13555
9.00k
    window->ViewportId = viewport->ID;
13556
9.00k
    window->ViewportOwned = (viewport->Window == window);
13557
9.00k
}
13558
13559
static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window)
13560
0
{
13561
    // Tooltips and menus are not automatically forced into their own viewport when the NoMerge flag is set, however the multiplication of viewports makes them more likely to protrude and create their own.
13562
0
    ImGuiContext& g = *GImGui;
13563
0
    if (g.IO.ConfigViewportsNoAutoMerge || (window->WindowClass.ViewportFlagsOverrideSet & ImGuiViewportFlags_NoAutoMerge))
13564
0
        if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
13565
0
            if (!window->DockIsActive)
13566
0
                if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip)) == 0)
13567
0
                    if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || (window->Flags & ImGuiWindowFlags_Modal) != 0)
13568
0
                        return true;
13569
0
    return false;
13570
0
}
13571
13572
static bool ImGui::UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
13573
0
{
13574
0
    ImGuiContext& g = *GImGui;
13575
0
    if (window->Viewport == viewport)
13576
0
        return false;
13577
0
    if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) == 0)
13578
0
        return false;
13579
0
    if ((viewport->Flags & ImGuiViewportFlags_Minimized) != 0)
13580
0
        return false;
13581
0
    if (!viewport->GetMainRect().Contains(window->Rect()))
13582
0
        return false;
13583
0
    if (GetWindowAlwaysWantOwnViewport(window))
13584
0
        return false;
13585
13586
    // FIXME: Can't use g.WindowsFocusOrder[] for root windows only as we care about Z order. If we maintained a DisplayOrder along with FocusOrder we could..
13587
0
    for (int n = 0; n < g.Windows.Size; n++)
13588
0
    {
13589
0
        ImGuiWindow* window_behind = g.Windows[n];
13590
0
        if (window_behind == window)
13591
0
            break;
13592
0
        if (window_behind->WasActive && window_behind->ViewportOwned && !(window_behind->Flags & ImGuiWindowFlags_ChildWindow))
13593
0
            if (window_behind->Viewport->GetMainRect().Overlaps(window->Rect()))
13594
0
                return false;
13595
0
    }
13596
13597
    // Move to the existing viewport, Move child/hosted windows as well (FIXME-OPT: iterate child)
13598
0
    ImGuiViewportP* old_viewport = window->Viewport;
13599
0
    if (window->ViewportOwned)
13600
0
        for (int n = 0; n < g.Windows.Size; n++)
13601
0
            if (g.Windows[n]->Viewport == old_viewport)
13602
0
                SetWindowViewport(g.Windows[n], viewport);
13603
0
    SetWindowViewport(window, viewport);
13604
0
    BringWindowToDisplayFront(window);
13605
13606
0
    return true;
13607
0
}
13608
13609
// FIXME: handle 0 to N host viewports
13610
static bool ImGui::UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window)
13611
0
{
13612
0
    ImGuiContext& g = *GImGui;
13613
0
    return UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0]);
13614
0
}
13615
13616
// Translate Dear ImGui windows when a Host Viewport has been moved
13617
// (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
13618
void ImGui::TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& old_pos, const ImVec2& new_pos)
13619
0
{
13620
0
    ImGuiContext& g = *GImGui;
13621
0
    IM_ASSERT(viewport->Window == NULL && (viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows));
13622
13623
    // 1) We test if ImGuiConfigFlags_ViewportsEnable was just toggled, which allows us to conveniently
13624
    // translate imgui windows from OS-window-local to absolute coordinates or vice-versa.
13625
    // 2) If it's not going to fit into the new size, keep it at same absolute position.
13626
    // One problem with this is that most Win32 applications doesn't update their render while dragging,
13627
    // and so the window will appear to teleport when releasing the mouse.
13628
0
    const bool translate_all_windows = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable);
13629
0
    ImRect test_still_fit_rect(old_pos, old_pos + viewport->Size);
13630
0
    ImVec2 delta_pos = new_pos - old_pos;
13631
0
    for (int window_n = 0; window_n < g.Windows.Size; window_n++) // FIXME-OPT
13632
0
        if (translate_all_windows || (g.Windows[window_n]->Viewport == viewport && test_still_fit_rect.Contains(g.Windows[window_n]->Rect())))
13633
0
            TranslateWindow(g.Windows[window_n], delta_pos);
13634
0
}
13635
13636
// Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!)
13637
void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale)
13638
0
{
13639
0
    ImGuiContext& g = *GImGui;
13640
0
    if (viewport->Window)
13641
0
    {
13642
0
        ScaleWindow(viewport->Window, scale);
13643
0
    }
13644
0
    else
13645
0
    {
13646
0
        for (int i = 0; i != g.Windows.Size; i++)
13647
0
            if (g.Windows[i]->Viewport == viewport)
13648
0
                ScaleWindow(g.Windows[i], scale);
13649
0
    }
13650
0
}
13651
13652
// If the backend doesn't set MouseLastHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs, we do a search ourselves.
13653
// A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
13654
// B) It requires Platform_GetWindowFocus to be implemented by backend.
13655
ImGuiViewportP* ImGui::FindHoveredViewportFromPlatformWindowStack(const ImVec2& mouse_platform_pos)
13656
0
{
13657
0
    ImGuiContext& g = *GImGui;
13658
0
    ImGuiViewportP* best_candidate = NULL;
13659
0
    for (int n = 0; n < g.Viewports.Size; n++)
13660
0
    {
13661
0
        ImGuiViewportP* viewport = g.Viewports[n];
13662
0
        if (!(viewport->Flags & (ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_Minimized)) && viewport->GetMainRect().Contains(mouse_platform_pos))
13663
0
            if (best_candidate == NULL || best_candidate->LastFrontMostStampCount < viewport->LastFrontMostStampCount)
13664
0
                best_candidate = viewport;
13665
0
    }
13666
0
    return best_candidate;
13667
0
}
13668
13669
// Update viewports and monitor infos
13670
// Note that this is running even if 'ImGuiConfigFlags_ViewportsEnable' is not set, in order to clear unused viewports (if any) and update monitor info.
13671
static void ImGui::UpdateViewportsNewFrame()
13672
3.00k
{
13673
3.00k
    ImGuiContext& g = *GImGui;
13674
3.00k
    IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size);
13675
13676
    // Update Minimized status (we need it first in order to decide if we'll apply Pos/Size of the main viewport)
13677
3.00k
    const bool viewports_enabled = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != 0;
13678
3.00k
    if (viewports_enabled)
13679
0
    {
13680
0
        for (int n = 0; n < g.Viewports.Size; n++)
13681
0
        {
13682
0
            ImGuiViewportP* viewport = g.Viewports[n];
13683
0
            const bool platform_funcs_available = viewport->PlatformWindowCreated;
13684
0
            if (g.PlatformIO.Platform_GetWindowMinimized && platform_funcs_available)
13685
0
            {
13686
0
                bool minimized = g.PlatformIO.Platform_GetWindowMinimized(viewport);
13687
0
                if (minimized)
13688
0
                    viewport->Flags |= ImGuiViewportFlags_Minimized;
13689
0
                else
13690
0
                    viewport->Flags &= ~ImGuiViewportFlags_Minimized;
13691
0
            }
13692
0
        }
13693
0
    }
13694
13695
    // Create/update main viewport with current platform position.
13696
    // FIXME-VIEWPORT: Size is driven by backend/user code for backward-compatibility but we should aim to make this more consistent.
13697
3.00k
    ImGuiViewportP* main_viewport = g.Viewports[0];
13698
3.00k
    IM_ASSERT(main_viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID);
13699
3.00k
    IM_ASSERT(main_viewport->Window == NULL);
13700
3.00k
    ImVec2 main_viewport_pos = viewports_enabled ? g.PlatformIO.Platform_GetWindowPos(main_viewport) : ImVec2(0.0f, 0.0f);
13701
3.00k
    ImVec2 main_viewport_size = g.IO.DisplaySize;
13702
3.00k
    if (viewports_enabled && (main_viewport->Flags & ImGuiViewportFlags_Minimized))
13703
0
    {
13704
0
        main_viewport_pos = main_viewport->Pos;    // Preserve last pos/size when minimized (FIXME: We don't do the same for Size outside of the viewport path)
13705
0
        main_viewport_size = main_viewport->Size;
13706
0
    }
13707
3.00k
    AddUpdateViewport(NULL, IMGUI_VIEWPORT_DEFAULT_ID, main_viewport_pos, main_viewport_size, ImGuiViewportFlags_OwnedByApp | ImGuiViewportFlags_CanHostOtherWindows);
13708
13709
3.00k
    g.CurrentDpiScale = 0.0f;
13710
3.00k
    g.CurrentViewport = NULL;
13711
3.00k
    g.MouseViewport = NULL;
13712
6.00k
    for (int n = 0; n < g.Viewports.Size; n++)
13713
3.00k
    {
13714
3.00k
        ImGuiViewportP* viewport = g.Viewports[n];
13715
3.00k
        viewport->Idx = n;
13716
13717
        // Erase unused viewports
13718
3.00k
        if (n > 0 && viewport->LastFrameActive < g.FrameCount - 2)
13719
0
        {
13720
0
            DestroyViewport(viewport);
13721
0
            n--;
13722
0
            continue;
13723
0
        }
13724
13725
3.00k
        const bool platform_funcs_available = viewport->PlatformWindowCreated;
13726
3.00k
        if (viewports_enabled)
13727
0
        {
13728
            // Update Position and Size (from Platform Window to ImGui) if requested.
13729
            // We do it early in the frame instead of waiting for UpdatePlatformWindows() to avoid a frame of lag when moving/resizing using OS facilities.
13730
0
            if (!(viewport->Flags & ImGuiViewportFlags_Minimized) && platform_funcs_available)
13731
0
            {
13732
                // Viewport->WorkPos and WorkSize will be updated below
13733
0
                if (viewport->PlatformRequestMove)
13734
0
                    viewport->Pos = viewport->LastPlatformPos = g.PlatformIO.Platform_GetWindowPos(viewport);
13735
0
                if (viewport->PlatformRequestResize)
13736
0
                    viewport->Size = viewport->LastPlatformSize = g.PlatformIO.Platform_GetWindowSize(viewport);
13737
0
            }
13738
0
        }
13739
13740
        // Update/copy monitor info
13741
3.00k
        UpdateViewportPlatformMonitor(viewport);
13742
13743
        // Lock down space taken by menu bars and status bars, reset the offset for functions like BeginMainMenuBar() to alter them again.
13744
3.00k
        viewport->WorkOffsetMin = viewport->BuildWorkOffsetMin;
13745
3.00k
        viewport->WorkOffsetMax = viewport->BuildWorkOffsetMax;
13746
3.00k
        viewport->BuildWorkOffsetMin = viewport->BuildWorkOffsetMax = ImVec2(0.0f, 0.0f);
13747
3.00k
        viewport->UpdateWorkRect();
13748
13749
        // Reset alpha every frame. Users of transparency (docking) needs to request a lower alpha back.
13750
3.00k
        viewport->Alpha = 1.0f;
13751
13752
        // Translate Dear ImGui windows when a Host Viewport has been moved
13753
        // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
13754
3.00k
        const ImVec2 viewport_delta_pos = viewport->Pos - viewport->LastPos;
13755
3.00k
        if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) && (viewport_delta_pos.x != 0.0f || viewport_delta_pos.y != 0.0f))
13756
0
            TranslateWindowsInViewport(viewport, viewport->LastPos, viewport->Pos);
13757
13758
        // Update DPI scale
13759
3.00k
        float new_dpi_scale;
13760
3.00k
        if (g.PlatformIO.Platform_GetWindowDpiScale && platform_funcs_available)
13761
0
            new_dpi_scale = g.PlatformIO.Platform_GetWindowDpiScale(viewport);
13762
3.00k
        else if (viewport->PlatformMonitor != -1)
13763
0
            new_dpi_scale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
13764
3.00k
        else
13765
3.00k
            new_dpi_scale = (viewport->DpiScale != 0.0f) ? viewport->DpiScale : 1.0f;
13766
3.00k
        if (viewport->DpiScale != 0.0f && new_dpi_scale != viewport->DpiScale)
13767
0
        {
13768
0
            float scale_factor = new_dpi_scale / viewport->DpiScale;
13769
0
            if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports)
13770
0
                ScaleWindowsInViewport(viewport, scale_factor);
13771
            //if (viewport == GetMainViewport())
13772
            //    g.PlatformInterface.SetWindowSize(viewport, viewport->Size * scale_factor);
13773
13774
            // Scale our window moving pivot so that the window will rescale roughly around the mouse position.
13775
            // FIXME-VIEWPORT: This currently creates a resizing feedback loop when a window is straddling a DPI transition border.
13776
            // (Minor: since our sizes do not perfectly linearly scale, deferring the click offset scale until we know the actual window scale ratio may get us slightly more precise mouse positioning.)
13777
            //if (g.MovingWindow != NULL && g.MovingWindow->Viewport == viewport)
13778
            //    g.ActiveIdClickOffset = ImFloor(g.ActiveIdClickOffset * scale_factor);
13779
0
        }
13780
3.00k
        viewport->DpiScale = new_dpi_scale;
13781
3.00k
    }
13782
13783
    // Update fallback monitor
13784
3.00k
    if (g.PlatformIO.Monitors.Size == 0)
13785
3.00k
    {
13786
3.00k
        ImGuiPlatformMonitor* monitor = &g.FallbackMonitor;
13787
3.00k
        monitor->MainPos = main_viewport->Pos;
13788
3.00k
        monitor->MainSize = main_viewport->Size;
13789
3.00k
        monitor->WorkPos = main_viewport->WorkPos;
13790
3.00k
        monitor->WorkSize = main_viewport->WorkSize;
13791
3.00k
        monitor->DpiScale = main_viewport->DpiScale;
13792
3.00k
    }
13793
13794
3.00k
    if (!viewports_enabled)
13795
3.00k
    {
13796
3.00k
        g.MouseViewport = main_viewport;
13797
3.00k
        return;
13798
3.00k
    }
13799
13800
    // Mouse handling: decide on the actual mouse viewport for this frame between the active/focused viewport and the hovered viewport.
13801
    // Note that 'viewport_hovered' should skip over any viewport that has the ImGuiViewportFlags_NoInputs flags set.
13802
0
    ImGuiViewportP* viewport_hovered = NULL;
13803
0
    if (g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport)
13804
0
    {
13805
0
        viewport_hovered = g.IO.MouseHoveredViewport ? (ImGuiViewportP*)FindViewportByID(g.IO.MouseHoveredViewport) : NULL;
13806
0
        if (viewport_hovered && (viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
13807
0
            viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos); // Backend failed to handle _NoInputs viewport: revert to our fallback.
13808
0
    }
13809
0
    else
13810
0
    {
13811
        // If the backend doesn't know how to honor ImGuiViewportFlags_NoInputs, we do a search ourselves. Note that this search:
13812
        // A) won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
13813
        // B) won't take account of how the backend apply parent<>child relationship to secondary viewports, which affects their Z order.
13814
        // C) uses LastFrameAsRefViewport as a flawed replacement for the last time a window was focused (we could/should fix that by introducing Focus functions in PlatformIO)
13815
0
        viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos);
13816
0
    }
13817
0
    if (viewport_hovered != NULL)
13818
0
        g.MouseLastHoveredViewport = viewport_hovered;
13819
0
    else if (g.MouseLastHoveredViewport == NULL)
13820
0
        g.MouseLastHoveredViewport = g.Viewports[0];
13821
13822
    // Update mouse reference viewport
13823
    // (when moving a window we aim at its viewport, but this will be overwritten below if we go in drag and drop mode)
13824
    // (MovingViewport->Viewport will be NULL in the rare situation where the window disappared while moving, set UpdateMouseMovingWindowNewFrame() for details)
13825
0
    if (g.MovingWindow && g.MovingWindow->Viewport)
13826
0
        g.MouseViewport = g.MovingWindow->Viewport;
13827
0
    else
13828
0
        g.MouseViewport = g.MouseLastHoveredViewport;
13829
13830
    // When dragging something, always refer to the last hovered viewport.
13831
    // - when releasing a moving window we will revert to aiming behind (at viewport_hovered)
13832
    // - when we are between viewports, our dragged preview will tend to show in the last viewport _even_ if we don't have tooltips in their viewports (when lacking monitor info)
13833
    // - consider the case of holding on a menu item to browse child menus: even thou a mouse button is held, there's no active id because menu items only react on mouse release.
13834
    // FIXME-VIEWPORT: This is essentially broken, when ImGuiBackendFlags_HasMouseHoveredViewport is set we want to trust when viewport_hovered==NULL and use that.
13835
0
    const bool is_mouse_dragging_with_an_expected_destination = g.DragDropActive;
13836
0
    if (is_mouse_dragging_with_an_expected_destination && viewport_hovered == NULL)
13837
0
        viewport_hovered = g.MouseLastHoveredViewport;
13838
0
    if (is_mouse_dragging_with_an_expected_destination || g.ActiveId == 0 || !IsAnyMouseDown())
13839
0
        if (viewport_hovered != NULL && viewport_hovered != g.MouseViewport && !(viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
13840
0
            g.MouseViewport = viewport_hovered;
13841
13842
0
    IM_ASSERT(g.MouseViewport != NULL);
13843
0
}
13844
13845
// Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
13846
static void ImGui::UpdateViewportsEndFrame()
13847
3.00k
{
13848
3.00k
    ImGuiContext& g = *GImGui;
13849
3.00k
    g.PlatformIO.Viewports.resize(0);
13850
6.00k
    for (int i = 0; i < g.Viewports.Size; i++)
13851
3.00k
    {
13852
3.00k
        ImGuiViewportP* viewport = g.Viewports[i];
13853
3.00k
        viewport->LastPos = viewport->Pos;
13854
3.00k
        if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0.0f || viewport->Size.y <= 0.0f)
13855
0
            if (i > 0) // Always include main viewport in the list
13856
0
                continue;
13857
3.00k
        if (viewport->Window && !IsWindowActiveAndVisible(viewport->Window))
13858
0
            continue;
13859
3.00k
        if (i > 0)
13860
3.00k
            IM_ASSERT(viewport->Window != NULL);
13861
3.00k
        g.PlatformIO.Viewports.push_back(viewport);
13862
3.00k
    }
13863
3.00k
    g.Viewports[0]->ClearRequestFlags(); // Clear main viewport flags because UpdatePlatformWindows() won't do it and may not even be called
13864
3.00k
}
13865
13866
// FIXME: We should ideally refactor the system to call this every frame (we currently don't)
13867
ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& pos, const ImVec2& size, ImGuiViewportFlags flags)
13868
3.00k
{
13869
3.00k
    ImGuiContext& g = *GImGui;
13870
3.00k
    IM_ASSERT(id != 0);
13871
13872
3.00k
    flags |= ImGuiViewportFlags_IsPlatformWindow;
13873
3.00k
    if (window != NULL)
13874
0
    {
13875
0
        if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window)
13876
0
            flags |= ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_NoFocusOnAppearing;
13877
0
        if ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs))
13878
0
            flags |= ImGuiViewportFlags_NoInputs;
13879
0
        if (window->Flags & ImGuiWindowFlags_NoFocusOnAppearing)
13880
0
            flags |= ImGuiViewportFlags_NoFocusOnAppearing;
13881
0
    }
13882
13883
3.00k
    ImGuiViewportP* viewport = (ImGuiViewportP*)FindViewportByID(id);
13884
3.00k
    if (viewport)
13885
3.00k
    {
13886
        // Always update for main viewport as we are already pulling correct platform pos/size (see #4900)
13887
3.00k
        if (!viewport->PlatformRequestMove || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
13888
3.00k
            viewport->Pos = pos;
13889
3.00k
        if (!viewport->PlatformRequestResize || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
13890
3.00k
            viewport->Size = size;
13891
3.00k
        viewport->Flags = flags | (viewport->Flags & ImGuiViewportFlags_Minimized); // Preserve existing flags
13892
3.00k
    }
13893
0
    else
13894
0
    {
13895
        // New viewport
13896
0
        viewport = IM_NEW(ImGuiViewportP)();
13897
0
        viewport->ID = id;
13898
0
        viewport->Idx = g.Viewports.Size;
13899
0
        viewport->Pos = viewport->LastPos = pos;
13900
0
        viewport->Size = size;
13901
0
        viewport->Flags = flags;
13902
0
        UpdateViewportPlatformMonitor(viewport);
13903
0
        g.Viewports.push_back(viewport);
13904
0
        IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Add Viewport %08X '%s'\n", id, window ? window->Name : "<NULL>");
13905
13906
        // We normally setup for all viewports in NewFrame() but here need to handle the mid-frame creation of a new viewport.
13907
        // We need to extend the fullscreen clip rect so the OverlayDrawList clip is correct for that the first frame
13908
0
        g.DrawListSharedData.ClipRectFullscreen.x = ImMin(g.DrawListSharedData.ClipRectFullscreen.x, viewport->Pos.x);
13909
0
        g.DrawListSharedData.ClipRectFullscreen.y = ImMin(g.DrawListSharedData.ClipRectFullscreen.y, viewport->Pos.y);
13910
0
        g.DrawListSharedData.ClipRectFullscreen.z = ImMax(g.DrawListSharedData.ClipRectFullscreen.z, viewport->Pos.x + viewport->Size.x);
13911
0
        g.DrawListSharedData.ClipRectFullscreen.w = ImMax(g.DrawListSharedData.ClipRectFullscreen.w, viewport->Pos.y + viewport->Size.y);
13912
13913
        // Store initial DpiScale before the OS platform window creation, based on expected monitor data.
13914
        // This is so we can select an appropriate font size on the first frame of our window lifetime
13915
0
        if (viewport->PlatformMonitor != -1)
13916
0
            viewport->DpiScale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
13917
0
    }
13918
13919
3.00k
    viewport->Window = window;
13920
3.00k
    viewport->LastFrameActive = g.FrameCount;
13921
3.00k
    viewport->UpdateWorkRect();
13922
3.00k
    IM_ASSERT(window == NULL || viewport->ID == window->ID);
13923
13924
3.00k
    if (window != NULL)
13925
0
        window->ViewportOwned = true;
13926
13927
3.00k
    return viewport;
13928
3.00k
}
13929
13930
static void ImGui::DestroyViewport(ImGuiViewportP* viewport)
13931
0
{
13932
    // Clear references to this viewport in windows (window->ViewportId becomes the master data)
13933
0
    ImGuiContext& g = *GImGui;
13934
0
    for (int window_n = 0; window_n < g.Windows.Size; window_n++)
13935
0
    {
13936
0
        ImGuiWindow* window = g.Windows[window_n];
13937
0
        if (window->Viewport != viewport)
13938
0
            continue;
13939
0
        window->Viewport = NULL;
13940
0
        window->ViewportOwned = false;
13941
0
    }
13942
0
    if (viewport == g.MouseLastHoveredViewport)
13943
0
        g.MouseLastHoveredViewport = NULL;
13944
13945
    // Destroy
13946
0
    IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Delete Viewport %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
13947
0
    DestroyPlatformWindow(viewport); // In most circumstances the platform window will already be destroyed here.
13948
0
    IM_ASSERT(g.PlatformIO.Viewports.contains(viewport) == false);
13949
0
    IM_ASSERT(g.Viewports[viewport->Idx] == viewport);
13950
0
    g.Viewports.erase(g.Viewports.Data + viewport->Idx);
13951
0
    IM_DELETE(viewport);
13952
0
}
13953
13954
// FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten.
13955
static void ImGui::WindowSelectViewport(ImGuiWindow* window)
13956
9.00k
{
13957
9.00k
    ImGuiContext& g = *GImGui;
13958
9.00k
    ImGuiWindowFlags flags = window->Flags;
13959
9.00k
    window->ViewportAllowPlatformMonitorExtend = -1;
13960
13961
    // Restore main viewport if multi-viewport is not supported by the backend
13962
9.00k
    ImGuiViewportP* main_viewport = (ImGuiViewportP*)(void*)GetMainViewport();
13963
9.00k
    if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
13964
9.00k
    {
13965
9.00k
        SetWindowViewport(window, main_viewport);
13966
9.00k
        return;
13967
9.00k
    }
13968
0
    window->ViewportOwned = false;
13969
13970
    // Appearing popups reset their viewport so they can inherit again
13971
0
    if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && window->Appearing)
13972
0
    {
13973
0
        window->Viewport = NULL;
13974
0
        window->ViewportId = 0;
13975
0
    }
13976
13977
0
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport) == 0)
13978
0
    {
13979
        // By default inherit from parent window
13980
0
        if (window->Viewport == NULL && window->ParentWindow && (!window->ParentWindow->IsFallbackWindow || window->ParentWindow->WasActive))
13981
0
            window->Viewport = window->ParentWindow->Viewport;
13982
13983
        // Attempt to restore saved viewport id (= window that hasn't been activated yet), try to restore the viewport based on saved 'window->ViewportPos' restored from .ini file
13984
0
        if (window->Viewport == NULL && window->ViewportId != 0)
13985
0
        {
13986
0
            window->Viewport = (ImGuiViewportP*)FindViewportByID(window->ViewportId);
13987
0
            if (window->Viewport == NULL && window->ViewportPos.x != FLT_MAX && window->ViewportPos.y != FLT_MAX)
13988
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->ViewportPos, window->Size, ImGuiViewportFlags_None);
13989
0
        }
13990
0
    }
13991
13992
0
    bool lock_viewport = false;
13993
0
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport)
13994
0
    {
13995
        // Code explicitly request a viewport
13996
0
        window->Viewport = (ImGuiViewportP*)FindViewportByID(g.NextWindowData.ViewportId);
13997
0
        window->ViewportId = g.NextWindowData.ViewportId; // Store ID even if Viewport isn't resolved yet.
13998
0
        lock_viewport = true;
13999
0
    }
14000
0
    else if ((flags & ImGuiWindowFlags_ChildWindow) || (flags & ImGuiWindowFlags_ChildMenu))
14001
0
    {
14002
        // Always inherit viewport from parent window
14003
0
        if (window->DockNode && window->DockNode->HostWindow)
14004
0
            IM_ASSERT(window->DockNode->HostWindow->Viewport == window->ParentWindow->Viewport);
14005
0
        window->Viewport = window->ParentWindow->Viewport;
14006
0
    }
14007
0
    else if (window->DockNode && window->DockNode->HostWindow)
14008
0
    {
14009
        // This covers the "always inherit viewport from parent window" case for when a window reattach to a node that was just created mid-frame
14010
0
        window->Viewport = window->DockNode->HostWindow->Viewport;
14011
0
    }
14012
0
    else if (flags & ImGuiWindowFlags_Tooltip)
14013
0
    {
14014
0
        window->Viewport = g.MouseViewport;
14015
0
    }
14016
0
    else if (GetWindowAlwaysWantOwnViewport(window))
14017
0
    {
14018
0
        window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
14019
0
    }
14020
0
    else if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window && IsMousePosValid())
14021
0
    {
14022
0
        if (window->Viewport != NULL && window->Viewport->Window == window)
14023
0
            window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
14024
0
    }
14025
0
    else
14026
0
    {
14027
        // Merge into host viewport?
14028
        // We cannot test window->ViewportOwned as it set lower in the function.
14029
        // Testing (g.ActiveId == 0 || g.ActiveIdAllowOverlap) to avoid merging during a short-term widget interaction. Main intent was to avoid during resize (see #4212)
14030
0
        bool try_to_merge_into_host_viewport = (window->Viewport && window == window->Viewport->Window && (g.ActiveId == 0 || g.ActiveIdAllowOverlap));
14031
0
        if (try_to_merge_into_host_viewport)
14032
0
            UpdateTryMergeWindowIntoHostViewports(window);
14033
0
    }
14034
14035
    // Fallback: merge in default viewport if z-order matches, otherwise create a new viewport
14036
0
    if (window->Viewport == NULL)
14037
0
        if (!UpdateTryMergeWindowIntoHostViewport(window, main_viewport))
14038
0
            window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
14039
14040
    // Mark window as allowed to protrude outside of its viewport and into the current monitor
14041
0
    if (!lock_viewport)
14042
0
    {
14043
0
        if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
14044
0
        {
14045
            // We need to take account of the possibility that mouse may become invalid.
14046
            // Popups/Tooltip always set ViewportAllowPlatformMonitorExtend so GetWindowAllowedExtentRect() will return full monitor bounds.
14047
0
            ImVec2 mouse_ref = (flags & ImGuiWindowFlags_Tooltip) ? g.IO.MousePos : g.BeginPopupStack.back().OpenMousePos;
14048
0
            bool use_mouse_ref = (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow);
14049
0
            bool mouse_valid = IsMousePosValid(&mouse_ref);
14050
0
            if ((window->Appearing || (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_ChildMenu))) && (!use_mouse_ref || mouse_valid))
14051
0
                window->ViewportAllowPlatformMonitorExtend = FindPlatformMonitorForPos((use_mouse_ref && mouse_valid) ? mouse_ref : NavCalcPreferredRefPos());
14052
0
            else
14053
0
                window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
14054
0
        }
14055
0
        else if (window->Viewport && window != window->Viewport->Window && window->Viewport->Window && !(flags & ImGuiWindowFlags_ChildWindow) && window->DockNode == NULL)
14056
0
        {
14057
            // When called from Begin() we don't have access to a proper version of the Hidden flag yet, so we replicate this code.
14058
0
            const bool will_be_visible = (window->DockIsActive && !window->DockTabIsVisible) ? false : true;
14059
0
            if ((window->Flags & ImGuiWindowFlags_DockNodeHost) && window->Viewport->LastFrameActive < g.FrameCount && will_be_visible)
14060
0
            {
14061
                // Steal/transfer ownership
14062
0
                IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' steal Viewport %08X from Window '%s'\n", window->Name, window->Viewport->ID, window->Viewport->Window->Name);
14063
0
                window->Viewport->Window = window;
14064
0
                window->Viewport->ID = window->ID;
14065
0
                window->Viewport->LastNameHash = 0;
14066
0
            }
14067
0
            else if (!UpdateTryMergeWindowIntoHostViewports(window)) // Merge?
14068
0
            {
14069
                // New viewport
14070
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
14071
0
            }
14072
0
        }
14073
0
        else if (window->ViewportAllowPlatformMonitorExtend < 0 && (flags & ImGuiWindowFlags_ChildWindow) == 0)
14074
0
        {
14075
            // Regular (non-child, non-popup) windows by default are also allowed to protrude
14076
            // Child windows are kept contained within their parent.
14077
0
            window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
14078
0
        }
14079
0
    }
14080
14081
    // Update flags
14082
0
    window->ViewportOwned = (window == window->Viewport->Window);
14083
0
    window->ViewportId = window->Viewport->ID;
14084
14085
    // If the OS window has a title bar, hide our imgui title bar
14086
    //if (window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration))
14087
    //    window->Flags |= ImGuiWindowFlags_NoTitleBar;
14088
0
}
14089
14090
void ImGui::WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack)
14091
0
{
14092
0
    ImGuiContext& g = *GImGui;
14093
14094
0
    bool viewport_rect_changed = false;
14095
14096
    // Synchronize window --> viewport in most situations
14097
    // Synchronize viewport -> window in case the platform window has been moved or resized from the OS/WM
14098
0
    if (window->Viewport->PlatformRequestMove)
14099
0
    {
14100
0
        window->Pos = window->Viewport->Pos;
14101
0
        MarkIniSettingsDirty(window);
14102
0
    }
14103
0
    else if (memcmp(&window->Viewport->Pos, &window->Pos, sizeof(window->Pos)) != 0)
14104
0
    {
14105
0
        viewport_rect_changed = true;
14106
0
        window->Viewport->Pos = window->Pos;
14107
0
    }
14108
14109
0
    if (window->Viewport->PlatformRequestResize)
14110
0
    {
14111
0
        window->Size = window->SizeFull = window->Viewport->Size;
14112
0
        MarkIniSettingsDirty(window);
14113
0
    }
14114
0
    else if (memcmp(&window->Viewport->Size, &window->Size, sizeof(window->Size)) != 0)
14115
0
    {
14116
0
        viewport_rect_changed = true;
14117
0
        window->Viewport->Size = window->Size;
14118
0
    }
14119
0
    window->Viewport->UpdateWorkRect();
14120
14121
    // The viewport may have changed monitor since the global update in UpdateViewportsNewFrame()
14122
    // Either a SetNextWindowPos() call in the current frame or a SetWindowPos() call in the previous frame may have this effect.
14123
0
    if (viewport_rect_changed)
14124
0
        UpdateViewportPlatformMonitor(window->Viewport);
14125
14126
    // Update common viewport flags
14127
0
    const ImGuiViewportFlags viewport_flags_to_clear = ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration | ImGuiViewportFlags_NoRendererClear;
14128
0
    ImGuiViewportFlags viewport_flags = window->Viewport->Flags & ~viewport_flags_to_clear;
14129
0
    ImGuiWindowFlags window_flags = window->Flags;
14130
0
    const bool is_modal = (window_flags & ImGuiWindowFlags_Modal) != 0;
14131
0
    const bool is_short_lived_floating_window = (window_flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0;
14132
0
    if (window_flags & ImGuiWindowFlags_Tooltip)
14133
0
        viewport_flags |= ImGuiViewportFlags_TopMost;
14134
0
    if ((g.IO.ConfigViewportsNoTaskBarIcon || is_short_lived_floating_window) && !is_modal)
14135
0
        viewport_flags |= ImGuiViewportFlags_NoTaskBarIcon;
14136
0
    if (g.IO.ConfigViewportsNoDecoration || is_short_lived_floating_window)
14137
0
        viewport_flags |= ImGuiViewportFlags_NoDecoration;
14138
14139
    // Not correct to set modal as topmost because:
14140
    // - Because other popups can be stacked above a modal (e.g. combo box in a modal)
14141
    // - ImGuiViewportFlags_TopMost is currently handled different in backends: in Win32 it is "appear top most" whereas in GLFW and SDL it is "stay topmost"
14142
    //if (flags & ImGuiWindowFlags_Modal)
14143
    //    viewport_flags |= ImGuiViewportFlags_TopMost;
14144
14145
    // For popups and menus that may be protruding out of their parent viewport, we enable _NoFocusOnClick so that clicking on them
14146
    // won't steal the OS focus away from their parent window (which may be reflected in OS the title bar decoration).
14147
    // Setting _NoFocusOnClick would technically prevent us from bringing back to front in case they are being covered by an OS window from a different app,
14148
    // but it shouldn't be much of a problem considering those are already popups that are closed when clicking elsewhere.
14149
0
    if (is_short_lived_floating_window && !is_modal)
14150
0
        viewport_flags |= ImGuiViewportFlags_NoFocusOnAppearing | ImGuiViewportFlags_NoFocusOnClick;
14151
14152
    // We can overwrite viewport flags using ImGuiWindowClass (advanced users)
14153
0
    if (window->WindowClass.ViewportFlagsOverrideSet)
14154
0
        viewport_flags |= window->WindowClass.ViewportFlagsOverrideSet;
14155
0
    if (window->WindowClass.ViewportFlagsOverrideClear)
14156
0
        viewport_flags &= ~window->WindowClass.ViewportFlagsOverrideClear;
14157
14158
    // We can also tell the backend that clearing the platform window won't be necessary,
14159
    // as our window background is filling the viewport and we have disabled BgAlpha.
14160
    // FIXME: Work on support for per-viewport transparency (#2766)
14161
0
    if (!(window_flags & ImGuiWindowFlags_NoBackground))
14162
0
        viewport_flags |= ImGuiViewportFlags_NoRendererClear;
14163
14164
0
    window->Viewport->Flags = viewport_flags;
14165
14166
    // Update parent viewport ID
14167
    // (the !IsFallbackWindow test mimic the one done in WindowSelectViewport())
14168
0
    if (window->WindowClass.ParentViewportId != (ImGuiID)-1)
14169
0
        window->Viewport->ParentViewportId = window->WindowClass.ParentViewportId;
14170
0
    else if ((window_flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && parent_window_in_stack && (!parent_window_in_stack->IsFallbackWindow || parent_window_in_stack->WasActive))
14171
0
        window->Viewport->ParentViewportId = parent_window_in_stack->Viewport->ID;
14172
0
    else
14173
0
        window->Viewport->ParentViewportId = g.IO.ConfigViewportsNoDefaultParent ? 0 : IMGUI_VIEWPORT_DEFAULT_ID;
14174
0
}
14175
14176
// Called by user at the end of the main loop, after EndFrame()
14177
// This will handle the creation/update of all OS windows via function defined in the ImGuiPlatformIO api.
14178
void ImGui::UpdatePlatformWindows()
14179
0
{
14180
0
    ImGuiContext& g = *GImGui;
14181
0
    IM_ASSERT(g.FrameCountEnded == g.FrameCount && "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?");
14182
0
    IM_ASSERT(g.FrameCountPlatformEnded < g.FrameCount);
14183
0
    g.FrameCountPlatformEnded = g.FrameCount;
14184
0
    if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
14185
0
        return;
14186
14187
    // Create/resize/destroy platform windows to match each active viewport.
14188
    // Skip the main viewport (index 0), which is always fully handled by the application!
14189
0
    for (int i = 1; i < g.Viewports.Size; i++)
14190
0
    {
14191
0
        ImGuiViewportP* viewport = g.Viewports[i];
14192
14193
        // Destroy platform window if the viewport hasn't been submitted or if it is hosting a hidden window
14194
        // (the implicit/fallback Debug##Default window will be registering its viewport then be disabled, causing a dummy DestroyPlatformWindow to be made each frame)
14195
0
        bool destroy_platform_window = false;
14196
0
        destroy_platform_window |= (viewport->LastFrameActive < g.FrameCount - 1);
14197
0
        destroy_platform_window |= (viewport->Window && !IsWindowActiveAndVisible(viewport->Window));
14198
0
        if (destroy_platform_window)
14199
0
        {
14200
0
            DestroyPlatformWindow(viewport);
14201
0
            continue;
14202
0
        }
14203
14204
        // New windows that appears directly in a new viewport won't always have a size on their first frame
14205
0
        if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0 || viewport->Size.y <= 0)
14206
0
            continue;
14207
14208
        // Create window
14209
0
        const bool is_new_platform_window = (viewport->PlatformWindowCreated == false);
14210
0
        if (is_new_platform_window)
14211
0
        {
14212
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Create Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
14213
0
            g.PlatformIO.Platform_CreateWindow(viewport);
14214
0
            if (g.PlatformIO.Renderer_CreateWindow != NULL)
14215
0
                g.PlatformIO.Renderer_CreateWindow(viewport);
14216
0
            viewport->LastNameHash = 0;
14217
0
            viewport->LastPlatformPos = viewport->LastPlatformSize = ImVec2(FLT_MAX, FLT_MAX); // By clearing those we'll enforce a call to Platform_SetWindowPos/Size below, before Platform_ShowWindow (FIXME: Is that necessary?)
14218
0
            viewport->LastRendererSize = viewport->Size;                                       // We don't need to call Renderer_SetWindowSize() as it is expected Renderer_CreateWindow() already did it.
14219
0
            viewport->PlatformWindowCreated = true;
14220
0
        }
14221
14222
        // Apply Position and Size (from ImGui to Platform/Renderer backends)
14223
0
        if ((viewport->LastPlatformPos.x != viewport->Pos.x || viewport->LastPlatformPos.y != viewport->Pos.y) && !viewport->PlatformRequestMove)
14224
0
            g.PlatformIO.Platform_SetWindowPos(viewport, viewport->Pos);
14225
0
        if ((viewport->LastPlatformSize.x != viewport->Size.x || viewport->LastPlatformSize.y != viewport->Size.y) && !viewport->PlatformRequestResize)
14226
0
            g.PlatformIO.Platform_SetWindowSize(viewport, viewport->Size);
14227
0
        if ((viewport->LastRendererSize.x != viewport->Size.x || viewport->LastRendererSize.y != viewport->Size.y) && g.PlatformIO.Renderer_SetWindowSize)
14228
0
            g.PlatformIO.Renderer_SetWindowSize(viewport, viewport->Size);
14229
0
        viewport->LastPlatformPos = viewport->Pos;
14230
0
        viewport->LastPlatformSize = viewport->LastRendererSize = viewport->Size;
14231
14232
        // Update title bar (if it changed)
14233
0
        if (ImGuiWindow* window_for_title = GetWindowForTitleDisplay(viewport->Window))
14234
0
        {
14235
0
            const char* title_begin = window_for_title->Name;
14236
0
            char* title_end = (char*)(intptr_t)FindRenderedTextEnd(title_begin);
14237
0
            const ImGuiID title_hash = ImHashStr(title_begin, title_end - title_begin);
14238
0
            if (viewport->LastNameHash != title_hash)
14239
0
            {
14240
0
                char title_end_backup_c = *title_end;
14241
0
                *title_end = 0; // Cut existing buffer short instead of doing an alloc/free, no small gain.
14242
0
                g.PlatformIO.Platform_SetWindowTitle(viewport, title_begin);
14243
0
                *title_end = title_end_backup_c;
14244
0
                viewport->LastNameHash = title_hash;
14245
0
            }
14246
0
        }
14247
14248
        // Update alpha (if it changed)
14249
0
        if (viewport->LastAlpha != viewport->Alpha && g.PlatformIO.Platform_SetWindowAlpha)
14250
0
            g.PlatformIO.Platform_SetWindowAlpha(viewport, viewport->Alpha);
14251
0
        viewport->LastAlpha = viewport->Alpha;
14252
14253
        // Optional, general purpose call to allow the backend to perform general book-keeping even if things haven't changed.
14254
0
        if (g.PlatformIO.Platform_UpdateWindow)
14255
0
            g.PlatformIO.Platform_UpdateWindow(viewport);
14256
14257
0
        if (is_new_platform_window)
14258
0
        {
14259
            // On startup ensure new platform window don't steal focus (give it a few frames, as nested contents may lead to viewport being created a few frames late)
14260
0
            if (g.FrameCount < 3)
14261
0
                viewport->Flags |= ImGuiViewportFlags_NoFocusOnAppearing;
14262
14263
            // Show window
14264
0
            g.PlatformIO.Platform_ShowWindow(viewport);
14265
14266
            // Even without focus, we assume the window becomes front-most.
14267
            // This is useful for our platform z-order heuristic when io.MouseHoveredViewport is not available.
14268
0
            if (viewport->LastFrontMostStampCount != g.ViewportFrontMostStampCount)
14269
0
                viewport->LastFrontMostStampCount = ++g.ViewportFrontMostStampCount;
14270
0
            }
14271
14272
        // Clear request flags
14273
0
        viewport->ClearRequestFlags();
14274
0
    }
14275
14276
    // Update our implicit z-order knowledge of platform windows, which is used when the backend cannot provide io.MouseHoveredViewport.
14277
    // When setting Platform_GetWindowFocus, it is expected that the platform backend can handle calls without crashing if it doesn't have data stored.
14278
    // FIXME-VIEWPORT: We should use this information to also set dear imgui-side focus, allowing us to handle os-level alt+tab.
14279
0
    if (g.PlatformIO.Platform_GetWindowFocus != NULL)
14280
0
    {
14281
0
        ImGuiViewportP* focused_viewport = NULL;
14282
0
        for (int n = 0; n < g.Viewports.Size && focused_viewport == NULL; n++)
14283
0
        {
14284
0
            ImGuiViewportP* viewport = g.Viewports[n];
14285
0
            if (viewport->PlatformWindowCreated)
14286
0
                if (g.PlatformIO.Platform_GetWindowFocus(viewport))
14287
0
                    focused_viewport = viewport;
14288
0
        }
14289
14290
        // Store a tag so we can infer z-order easily from all our windows
14291
        // We compare PlatformLastFocusedViewportId so newly created viewports with _NoFocusOnAppearing flag
14292
        // will keep the front most stamp instead of losing it back to their parent viewport.
14293
0
        if (focused_viewport && g.PlatformLastFocusedViewportId != focused_viewport->ID)
14294
0
        {
14295
0
            if (focused_viewport->LastFrontMostStampCount != g.ViewportFrontMostStampCount)
14296
0
                focused_viewport->LastFrontMostStampCount = ++g.ViewportFrontMostStampCount;
14297
0
            g.PlatformLastFocusedViewportId = focused_viewport->ID;
14298
0
        }
14299
0
    }
14300
0
}
14301
14302
// This is a default/basic function for performing the rendering/swap of multiple Platform Windows.
14303
// Custom renderers may prefer to not call this function at all, and instead iterate the publicly exposed platform data and handle rendering/sync themselves.
14304
// The Render/Swap functions stored in ImGuiPlatformIO are merely here to allow for this helper to exist, but you can do it yourself:
14305
//
14306
//    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
14307
//    for (int i = 1; i < platform_io.Viewports.Size; i++)
14308
//        if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
14309
//            MyRenderFunction(platform_io.Viewports[i], my_args);
14310
//    for (int i = 1; i < platform_io.Viewports.Size; i++)
14311
//        if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
14312
//            MySwapBufferFunction(platform_io.Viewports[i], my_args);
14313
//
14314
void ImGui::RenderPlatformWindowsDefault(void* platform_render_arg, void* renderer_render_arg)
14315
0
{
14316
    // Skip the main viewport (index 0), which is always fully handled by the application!
14317
0
    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
14318
0
    for (int i = 1; i < platform_io.Viewports.Size; i++)
14319
0
    {
14320
0
        ImGuiViewport* viewport = platform_io.Viewports[i];
14321
0
        if (viewport->Flags & ImGuiViewportFlags_Minimized)
14322
0
            continue;
14323
0
        if (platform_io.Platform_RenderWindow) platform_io.Platform_RenderWindow(viewport, platform_render_arg);
14324
0
        if (platform_io.Renderer_RenderWindow) platform_io.Renderer_RenderWindow(viewport, renderer_render_arg);
14325
0
    }
14326
0
    for (int i = 1; i < platform_io.Viewports.Size; i++)
14327
0
    {
14328
0
        ImGuiViewport* viewport = platform_io.Viewports[i];
14329
0
        if (viewport->Flags & ImGuiViewportFlags_Minimized)
14330
0
            continue;
14331
0
        if (platform_io.Platform_SwapBuffers) platform_io.Platform_SwapBuffers(viewport, platform_render_arg);
14332
0
        if (platform_io.Renderer_SwapBuffers) platform_io.Renderer_SwapBuffers(viewport, renderer_render_arg);
14333
0
    }
14334
0
}
14335
14336
static int ImGui::FindPlatformMonitorForPos(const ImVec2& pos)
14337
0
{
14338
0
    ImGuiContext& g = *GImGui;
14339
0
    for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
14340
0
    {
14341
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
14342
0
        if (ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize).Contains(pos))
14343
0
            return monitor_n;
14344
0
    }
14345
0
    return -1;
14346
0
}
14347
14348
// Search for the monitor with the largest intersection area with the given rectangle
14349
// We generally try to avoid searching loops but the monitor count should be very small here
14350
// FIXME-OPT: We could test the last monitor used for that viewport first, and early
14351
static int ImGui::FindPlatformMonitorForRect(const ImRect& rect)
14352
3.00k
{
14353
3.00k
    ImGuiContext& g = *GImGui;
14354
14355
3.00k
    const int monitor_count = g.PlatformIO.Monitors.Size;
14356
3.00k
    if (monitor_count <= 1)
14357
3.00k
        return monitor_count - 1;
14358
14359
    // Use a minimum threshold of 1.0f so a zero-sized rect won't false positive, and will still find the correct monitor given its position.
14360
    // This is necessary for tooltips which always resize down to zero at first.
14361
0
    const float surface_threshold = ImMax(rect.GetWidth() * rect.GetHeight() * 0.5f, 1.0f);
14362
0
    int best_monitor_n = -1;
14363
0
    float best_monitor_surface = 0.001f;
14364
14365
0
    for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size && best_monitor_surface < surface_threshold; monitor_n++)
14366
0
    {
14367
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
14368
0
        const ImRect monitor_rect = ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize);
14369
0
        if (monitor_rect.Contains(rect))
14370
0
            return monitor_n;
14371
0
        ImRect overlapping_rect = rect;
14372
0
        overlapping_rect.ClipWithFull(monitor_rect);
14373
0
        float overlapping_surface = overlapping_rect.GetWidth() * overlapping_rect.GetHeight();
14374
0
        if (overlapping_surface < best_monitor_surface)
14375
0
            continue;
14376
0
        best_monitor_surface = overlapping_surface;
14377
0
        best_monitor_n = monitor_n;
14378
0
    }
14379
0
    return best_monitor_n;
14380
0
}
14381
14382
// Update monitor from viewport rectangle (we'll use this info to clamp windows and save windows lost in a removed monitor)
14383
static void ImGui::UpdateViewportPlatformMonitor(ImGuiViewportP* viewport)
14384
3.00k
{
14385
3.00k
    viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(viewport->GetMainRect());
14386
3.00k
}
14387
14388
// Return value is always != NULL, but don't hold on it across frames.
14389
const ImGuiPlatformMonitor* ImGui::GetViewportPlatformMonitor(ImGuiViewport* viewport_p)
14390
0
{
14391
0
    ImGuiContext& g = *GImGui;
14392
0
    ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)viewport_p;
14393
0
    int monitor_idx = viewport->PlatformMonitor;
14394
0
    if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
14395
0
        return &g.PlatformIO.Monitors[monitor_idx];
14396
0
    return &g.FallbackMonitor;
14397
0
}
14398
14399
void ImGui::DestroyPlatformWindow(ImGuiViewportP* viewport)
14400
0
{
14401
0
    ImGuiContext& g = *GImGui;
14402
0
    if (viewport->PlatformWindowCreated)
14403
0
    {
14404
0
        if (g.PlatformIO.Renderer_DestroyWindow)
14405
0
            g.PlatformIO.Renderer_DestroyWindow(viewport);
14406
0
        if (g.PlatformIO.Platform_DestroyWindow)
14407
0
            g.PlatformIO.Platform_DestroyWindow(viewport);
14408
0
        IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL);
14409
14410
        // Don't clear PlatformWindowCreated for the main viewport, as we initially set that up to true in Initialize()
14411
        // The righter way may be to leave it to the backend to set this flag all-together, and made the flag public.
14412
0
        if (viewport->ID != IMGUI_VIEWPORT_DEFAULT_ID)
14413
0
            viewport->PlatformWindowCreated = false;
14414
0
    }
14415
0
    else
14416
0
    {
14417
0
        IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL && viewport->PlatformHandle == NULL);
14418
0
    }
14419
0
    viewport->RendererUserData = viewport->PlatformUserData = viewport->PlatformHandle = NULL;
14420
0
    viewport->ClearRequestFlags();
14421
0
}
14422
14423
void ImGui::DestroyPlatformWindows()
14424
0
{
14425
    // We call the destroy window on every viewport (including the main viewport, index 0) to give a chance to the backend
14426
    // to clear any data they may have stored in e.g. PlatformUserData, RendererUserData.
14427
    // It is convenient for the platform backend code to store something in the main viewport, in order for e.g. the mouse handling
14428
    // code to operator a consistent manner.
14429
    // It is expected that the backend can handle calls to Renderer_DestroyWindow/Platform_DestroyWindow without
14430
    // crashing if it doesn't have data stored.
14431
0
    ImGuiContext& g = *GImGui;
14432
0
    for (int i = 0; i < g.Viewports.Size; i++)
14433
0
        DestroyPlatformWindow(g.Viewports[i]);
14434
0
}
14435
14436
14437
//-----------------------------------------------------------------------------
14438
// [SECTION] DOCKING
14439
//-----------------------------------------------------------------------------
14440
// Docking: Internal Types
14441
// Docking: Forward Declarations
14442
// Docking: ImGuiDockContext
14443
// Docking: ImGuiDockContext Docking/Undocking functions
14444
// Docking: ImGuiDockNode
14445
// Docking: ImGuiDockNode Tree manipulation functions
14446
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
14447
// Docking: Builder Functions
14448
// Docking: Begin/End Support Functions (called from Begin/End)
14449
// Docking: Settings
14450
//-----------------------------------------------------------------------------
14451
14452
//-----------------------------------------------------------------------------
14453
// Typical Docking call flow: (root level is generally public API):
14454
//-----------------------------------------------------------------------------
14455
// - NewFrame()                               new dear imgui frame
14456
//    | DockContextNewFrameUpdateUndocking()  - process queued undocking requests
14457
//    | - DockContextProcessUndockWindow()    - process one window undocking request
14458
//    | - DockContextProcessUndockNode()      - process one whole node undocking request
14459
//    | DockContextNewFrameUpdateUndocking()  - process queue docking requests, create floating dock nodes
14460
//    | - update g.HoveredDockNode            - [debug] update node hovered by mouse
14461
//    | - DockContextProcessDock()            - process one docking request
14462
//    | - DockNodeUpdate()
14463
//    |   - DockNodeUpdateForRootNode()
14464
//    |     - DockNodeUpdateFlagsAndCollapse()
14465
//    |     - DockNodeFindInfo()
14466
//    |   - destroy unused node or tab bar
14467
//    |   - create dock node host window
14468
//    |      - Begin() etc.
14469
//    |   - DockNodeStartMouseMovingWindow()
14470
//    |   - DockNodeTreeUpdatePosSize()
14471
//    |   - DockNodeTreeUpdateSplitter()
14472
//    |   - draw node background
14473
//    |   - DockNodeUpdateTabBar()            - create/update tab bar for a docking node
14474
//    |     - DockNodeAddTabBar()
14475
//    |     - DockNodeUpdateWindowMenu()
14476
//    |     - DockNodeCalcTabBarLayout()
14477
//    |     - BeginTabBarEx()
14478
//    |     - TabItemEx() calls
14479
//    |     - EndTabBar()
14480
//    |   - BeginDockableDragDropTarget()
14481
//    |      - DockNodeUpdate()               - recurse into child nodes...
14482
//-----------------------------------------------------------------------------
14483
// - DockSpace()                              user submit a dockspace into a window
14484
//    | Begin(Child)                          - create a child window
14485
//    | DockNodeUpdate()                      - call main dock node update function
14486
//    | End(Child)
14487
//    | ItemSize()
14488
//-----------------------------------------------------------------------------
14489
// - Begin()
14490
//    | BeginDocked()
14491
//    | BeginDockableDragDropSource()
14492
//    | BeginDockableDragDropTarget()
14493
//    | - DockNodePreviewDockRender()
14494
//-----------------------------------------------------------------------------
14495
// - EndFrame()
14496
//    | DockContextEndFrame()
14497
//-----------------------------------------------------------------------------
14498
14499
//-----------------------------------------------------------------------------
14500
// Docking: Internal Types
14501
//-----------------------------------------------------------------------------
14502
// - ImGuiDockRequestType
14503
// - ImGuiDockRequest
14504
// - ImGuiDockPreviewData
14505
// - ImGuiDockNodeSettings
14506
// - ImGuiDockContext
14507
//-----------------------------------------------------------------------------
14508
14509
enum ImGuiDockRequestType
14510
{
14511
    ImGuiDockRequestType_None = 0,
14512
    ImGuiDockRequestType_Dock,
14513
    ImGuiDockRequestType_Undock,
14514
    ImGuiDockRequestType_Split                  // Split is the same as Dock but without a DockPayload
14515
};
14516
14517
struct ImGuiDockRequest
14518
{
14519
    ImGuiDockRequestType    Type;
14520
    ImGuiWindow*            DockTargetWindow;   // Destination/Target Window to dock into (may be a loose window or a DockNode, might be NULL in which case DockTargetNode cannot be NULL)
14521
    ImGuiDockNode*          DockTargetNode;     // Destination/Target Node to dock into
14522
    ImGuiWindow*            DockPayload;        // Source/Payload window to dock (may be a loose window or a DockNode), [Optional]
14523
    ImGuiDir                DockSplitDir;
14524
    float                   DockSplitRatio;
14525
    bool                    DockSplitOuter;
14526
    ImGuiWindow*            UndockTargetWindow;
14527
    ImGuiDockNode*          UndockTargetNode;
14528
14529
    ImGuiDockRequest()
14530
0
    {
14531
0
        Type = ImGuiDockRequestType_None;
14532
0
        DockTargetWindow = DockPayload = UndockTargetWindow = NULL;
14533
0
        DockTargetNode = UndockTargetNode = NULL;
14534
0
        DockSplitDir = ImGuiDir_None;
14535
0
        DockSplitRatio = 0.5f;
14536
0
        DockSplitOuter = false;
14537
0
    }
14538
};
14539
14540
struct ImGuiDockPreviewData
14541
{
14542
    ImGuiDockNode   FutureNode;
14543
    bool            IsDropAllowed;
14544
    bool            IsCenterAvailable;
14545
    bool            IsSidesAvailable;           // Hold your breath, grammar freaks..
14546
    bool            IsSplitDirExplicit;         // Set when hovered the drop rect (vs. implicit SplitDir==None when hovered the window)
14547
    ImGuiDockNode*  SplitNode;
14548
    ImGuiDir        SplitDir;
14549
    float           SplitRatio;
14550
    ImRect          DropRectsDraw[ImGuiDir_COUNT + 1];  // May be slightly different from hit-testing drop rects used in DockNodeCalcDropRects()
14551
14552
0
    ImGuiDockPreviewData() : FutureNode(0) { IsDropAllowed = IsCenterAvailable = IsSidesAvailable = IsSplitDirExplicit = false; SplitNode = NULL; SplitDir = ImGuiDir_None; SplitRatio = 0.f; for (int n = 0; n < IM_ARRAYSIZE(DropRectsDraw); n++) DropRectsDraw[n] = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); }
14553
};
14554
14555
// Persistent Settings data, stored contiguously in SettingsNodes (sizeof() ~32 bytes)
14556
struct ImGuiDockNodeSettings
14557
{
14558
    ImGuiID             ID;
14559
    ImGuiID             ParentNodeId;
14560
    ImGuiID             ParentWindowId;
14561
    ImGuiID             SelectedTabId;
14562
    signed char         SplitAxis;
14563
    char                Depth;
14564
    ImGuiDockNodeFlags  Flags;                  // NB: We save individual flags one by one in ascii format (ImGuiDockNodeFlags_SavedFlagsMask_)
14565
    ImVec2ih            Pos;
14566
    ImVec2ih            Size;
14567
    ImVec2ih            SizeRef;
14568
0
    ImGuiDockNodeSettings() { memset(this, 0, sizeof(*this)); SplitAxis = ImGuiAxis_None; }
14569
};
14570
14571
//-----------------------------------------------------------------------------
14572
// Docking: Forward Declarations
14573
//-----------------------------------------------------------------------------
14574
14575
namespace ImGui
14576
{
14577
    // ImGuiDockContext
14578
    static ImGuiDockNode*   DockContextAddNode(ImGuiContext* ctx, ImGuiID id);
14579
    static void             DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node);
14580
    static void             DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node);
14581
    static void             DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req);
14582
    static void             DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref = true);
14583
    static void             DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node);
14584
    static void             DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx);
14585
    static ImGuiDockNode*   DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window);
14586
    static void             DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count);
14587
    static void             DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id);                            // Use root_id==0 to add all
14588
14589
    // ImGuiDockNode
14590
    static void             DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar);
14591
    static void             DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
14592
    static void             DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
14593
    static ImGuiWindow*     DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id);
14594
    static void             DockNodeApplyPosSizeToWindows(ImGuiDockNode* node);
14595
    static void             DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id);
14596
    static void             DockNodeHideHostWindow(ImGuiDockNode* node);
14597
    static void             DockNodeUpdate(ImGuiDockNode* node);
14598
    static void             DockNodeUpdateForRootNode(ImGuiDockNode* node);
14599
    static void             DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node);
14600
    static void             DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node);
14601
    static void             DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window);
14602
    static void             DockNodeAddTabBar(ImGuiDockNode* node);
14603
    static void             DockNodeRemoveTabBar(ImGuiDockNode* node);
14604
    static ImGuiID          DockNodeUpdateWindowMenu(ImGuiDockNode* node, ImGuiTabBar* tab_bar);
14605
    static void             DockNodeUpdateVisibleFlag(ImGuiDockNode* node);
14606
    static void             DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window);
14607
    static bool             DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* payload_window);
14608
    static void             DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* preview_data, bool is_explicit_target, bool is_outer_docking);
14609
    static void             DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, const ImGuiDockPreviewData* preview_data);
14610
    static void             DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos);
14611
    static void             DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired);
14612
    static bool             DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_draw, bool outer_docking, ImVec2* test_mouse_pos);
14613
0
    static const char*      DockNodeGetHostWindowTitle(ImGuiDockNode* node, char* buf, int buf_size) { ImFormatString(buf, buf_size, "##DockNode_%02X", node->ID); return buf; }
14614
    static int              DockNodeGetTabOrder(ImGuiWindow* window);
14615
14616
    // ImGuiDockNode tree manipulations
14617
    static void             DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_first_child, float split_ratio, ImGuiDockNode* new_node);
14618
    static void             DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child);
14619
    static void             DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node = NULL);
14620
    static void             DockNodeTreeUpdateSplitter(ImGuiDockNode* node);
14621
    static ImGuiDockNode*   DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos);
14622
    static ImGuiDockNode*   DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node);
14623
14624
    // Settings
14625
    static void             DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id);
14626
    static void             DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count);
14627
    static ImGuiDockNodeSettings*   DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID node_id);
14628
    static void             DockSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
14629
    static void             DockSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
14630
    static void*            DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
14631
    static void             DockSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
14632
    static void             DockSettingsHandler_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf);
14633
}
14634
14635
//-----------------------------------------------------------------------------
14636
// Docking: ImGuiDockContext
14637
//-----------------------------------------------------------------------------
14638
// The lifetime model is different from the one of regular windows: we always create a ImGuiDockNode for each ImGuiDockNodeSettings,
14639
// or we always hold the entire docking node tree. Nodes are frequently hidden, e.g. if the window(s) or child nodes they host are not active.
14640
// At boot time only, we run a simple GC to remove nodes that have no references.
14641
// Because dock node settings (which are small, contiguous structures) are always mirrored by their corresponding dock nodes (more complete structures),
14642
// we can also very easily recreate the nodes from scratch given the settings data (this is what DockContextRebuild() does).
14643
// This is convenient as docking reconfiguration can be implemented by mostly poking at the simpler settings data.
14644
//-----------------------------------------------------------------------------
14645
// - DockContextInitialize()
14646
// - DockContextShutdown()
14647
// - DockContextClearNodes()
14648
// - DockContextRebuildNodes()
14649
// - DockContextNewFrameUpdateUndocking()
14650
// - DockContextNewFrameUpdateDocking()
14651
// - DockContextEndFrame()
14652
// - DockContextFindNodeByID()
14653
// - DockContextBindNodeToWindow()
14654
// - DockContextGenNodeID()
14655
// - DockContextAddNode()
14656
// - DockContextRemoveNode()
14657
// - ImGuiDockContextPruneNodeData
14658
// - DockContextPruneUnusedSettingsNodes()
14659
// - DockContextBuildNodesFromSettings()
14660
// - DockContextBuildAddWindowsToNodes()
14661
//-----------------------------------------------------------------------------
14662
14663
void ImGui::DockContextInitialize(ImGuiContext* ctx)
14664
1
{
14665
1
    ImGuiContext& g = *ctx;
14666
14667
    // Add .ini handle for persistent docking data
14668
1
    ImGuiSettingsHandler ini_handler;
14669
1
    ini_handler.TypeName = "Docking";
14670
1
    ini_handler.TypeHash = ImHashStr("Docking");
14671
1
    ini_handler.ClearAllFn = DockSettingsHandler_ClearAll;
14672
1
    ini_handler.ReadInitFn = DockSettingsHandler_ClearAll; // Also clear on read
14673
1
    ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen;
14674
1
    ini_handler.ReadLineFn = DockSettingsHandler_ReadLine;
14675
1
    ini_handler.ApplyAllFn = DockSettingsHandler_ApplyAll;
14676
1
    ini_handler.WriteAllFn = DockSettingsHandler_WriteAll;
14677
1
    g.SettingsHandlers.push_back(ini_handler);
14678
1
}
14679
14680
void ImGui::DockContextShutdown(ImGuiContext* ctx)
14681
0
{
14682
0
    ImGuiDockContext* dc  = &ctx->DockContext;
14683
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
14684
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
14685
0
            IM_DELETE(node);
14686
0
}
14687
14688
void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_settings_refs)
14689
0
{
14690
0
    IM_UNUSED(ctx);
14691
0
    IM_ASSERT(ctx == GImGui);
14692
0
    DockBuilderRemoveNodeDockedWindows(root_id, clear_settings_refs);
14693
0
    DockBuilderRemoveNodeChildNodes(root_id);
14694
0
}
14695
14696
// [DEBUG] This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch
14697
// (Different from DockSettingsHandler_ClearAll() + DockSettingsHandler_ApplyAll() because this reuses current settings!)
14698
void ImGui::DockContextRebuildNodes(ImGuiContext* ctx)
14699
0
{
14700
0
    ImGuiContext& g = *ctx;
14701
0
    ImGuiDockContext* dc = &ctx->DockContext;
14702
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRebuildNodes\n");
14703
0
    SaveIniSettingsToMemory();
14704
0
    ImGuiID root_id = 0; // Rebuild all
14705
0
    DockContextClearNodes(ctx, root_id, false);
14706
0
    DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
14707
0
    DockContextBuildAddWindowsToNodes(ctx, root_id);
14708
0
}
14709
14710
// Docking context update function, called by NewFrame()
14711
void ImGui::DockContextNewFrameUpdateUndocking(ImGuiContext* ctx)
14712
3.00k
{
14713
3.00k
    ImGuiContext& g = *ctx;
14714
3.00k
    ImGuiDockContext* dc = &ctx->DockContext;
14715
3.00k
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
14716
0
    {
14717
0
        if (dc->Nodes.Data.Size > 0 || dc->Requests.Size > 0)
14718
0
            DockContextClearNodes(ctx, 0, true);
14719
0
        return;
14720
0
    }
14721
14722
    // Setting NoSplit at runtime merges all nodes
14723
3.00k
    if (g.IO.ConfigDockingNoSplit)
14724
0
        for (int n = 0; n < dc->Nodes.Data.Size; n++)
14725
0
            if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
14726
0
                if (node->IsRootNode() && node->IsSplitNode())
14727
0
                {
14728
0
                    DockBuilderRemoveNodeChildNodes(node->ID);
14729
                    //dc->WantFullRebuild = true;
14730
0
                }
14731
14732
    // Process full rebuild
14733
#if 0
14734
    if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_C)))
14735
        dc->WantFullRebuild = true;
14736
#endif
14737
3.00k
    if (dc->WantFullRebuild)
14738
0
    {
14739
0
        DockContextRebuildNodes(ctx);
14740
0
        dc->WantFullRebuild = false;
14741
0
    }
14742
14743
    // Process Undocking requests (we need to process them _before_ the UpdateMouseMovingWindowNewFrame call in NewFrame)
14744
3.00k
    for (int n = 0; n < dc->Requests.Size; n++)
14745
0
    {
14746
0
        ImGuiDockRequest* req = &dc->Requests[n];
14747
0
        if (req->Type == ImGuiDockRequestType_Undock && req->UndockTargetWindow)
14748
0
            DockContextProcessUndockWindow(ctx, req->UndockTargetWindow);
14749
0
        else if (req->Type == ImGuiDockRequestType_Undock && req->UndockTargetNode)
14750
0
            DockContextProcessUndockNode(ctx, req->UndockTargetNode);
14751
0
    }
14752
3.00k
}
14753
14754
// Docking context update function, called by NewFrame()
14755
void ImGui::DockContextNewFrameUpdateDocking(ImGuiContext* ctx)
14756
3.00k
{
14757
3.00k
    ImGuiContext& g = *ctx;
14758
3.00k
    ImGuiDockContext* dc  = &ctx->DockContext;
14759
3.00k
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
14760
0
        return;
14761
14762
    // [DEBUG] Store hovered dock node.
14763
    // We could in theory use DockNodeTreeFindVisibleNodeByPos() on the root host dock node, but using ->DockNode is a good shortcut.
14764
    // Note this is mostly a debug thing and isn't actually used for docking target, because docking involve more detailed filtering.
14765
3.00k
    g.DebugHoveredDockNode = NULL;
14766
3.00k
    if (ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow)
14767
0
    {
14768
0
        if (hovered_window->DockNodeAsHost)
14769
0
            g.DebugHoveredDockNode = DockNodeTreeFindVisibleNodeByPos(hovered_window->DockNodeAsHost, g.IO.MousePos);
14770
0
        else if (hovered_window->RootWindow->DockNode)
14771
0
            g.DebugHoveredDockNode = hovered_window->RootWindow->DockNode;
14772
0
    }
14773
14774
    // Process Docking requests
14775
3.00k
    for (int n = 0; n < dc->Requests.Size; n++)
14776
0
        if (dc->Requests[n].Type == ImGuiDockRequestType_Dock)
14777
0
            DockContextProcessDock(ctx, &dc->Requests[n]);
14778
3.00k
    dc->Requests.resize(0);
14779
14780
    // Create windows for each automatic docking nodes
14781
    // We can have NULL pointers when we delete nodes, but because ID are recycled this should amortize nicely (and our node count will never be very high)
14782
3.00k
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
14783
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
14784
0
            if (node->IsFloatingNode())
14785
0
                DockNodeUpdate(node);
14786
3.00k
}
14787
14788
void ImGui::DockContextEndFrame(ImGuiContext* ctx)
14789
3.00k
{
14790
    // Draw backgrounds of node missing their window
14791
3.00k
    ImGuiContext& g = *ctx;
14792
3.00k
    ImGuiDockContext* dc = &g.DockContext;
14793
3.00k
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
14794
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
14795
0
            if (node->LastFrameActive == g.FrameCount && node->IsVisible && node->HostWindow && node->IsLeafNode() && !node->IsBgDrawnThisFrame)
14796
0
            {
14797
0
                ImRect bg_rect(node->Pos + ImVec2(0.0f, GetFrameHeight()), node->Pos + node->Size);
14798
0
                ImDrawFlags bg_rounding_flags = CalcRoundingFlagsForRectInRect(bg_rect, node->HostWindow->Rect(), DOCKING_SPLITTER_SIZE);
14799
0
                node->HostWindow->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
14800
0
                node->HostWindow->DrawList->AddRectFilled(bg_rect.Min, bg_rect.Max, node->LastBgColor, node->HostWindow->WindowRounding, bg_rounding_flags);
14801
0
            }
14802
3.00k
}
14803
14804
ImGuiDockNode* ImGui::DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id)
14805
0
{
14806
0
    return (ImGuiDockNode*)ctx->DockContext.Nodes.GetVoidPtr(id);
14807
0
}
14808
14809
ImGuiID ImGui::DockContextGenNodeID(ImGuiContext* ctx)
14810
0
{
14811
    // Generate an ID for new node (the exact ID value doesn't matter as long as it is not already used)
14812
    // FIXME-OPT FIXME-DOCK: This is suboptimal, even if the node count is small enough not to be a worry.0
14813
    // We should poke in ctx->Nodes to find a suitable ID faster. Even more so trivial that ctx->Nodes lookup is already sorted.
14814
0
    ImGuiID id = 0x0001;
14815
0
    while (DockContextFindNodeByID(ctx, id) != NULL)
14816
0
        id++;
14817
0
    return id;
14818
0
}
14819
14820
static ImGuiDockNode* ImGui::DockContextAddNode(ImGuiContext* ctx, ImGuiID id)
14821
0
{
14822
    // Generate an ID for the new node (the exact ID value doesn't matter as long as it is not already used) and add the first window.
14823
0
    ImGuiContext& g = *ctx;
14824
0
    if (id == 0)
14825
0
        id = DockContextGenNodeID(ctx);
14826
0
    else
14827
0
        IM_ASSERT(DockContextFindNodeByID(ctx, id) == NULL);
14828
14829
    // We don't set node->LastFrameAlive on construction. Nodes are always created at all time to reflect .ini settings!
14830
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextAddNode 0x%08X\n", id);
14831
0
    ImGuiDockNode* node = IM_NEW(ImGuiDockNode)(id);
14832
0
    ctx->DockContext.Nodes.SetVoidPtr(node->ID, node);
14833
0
    return node;
14834
0
}
14835
14836
static void ImGui::DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node)
14837
0
{
14838
0
    ImGuiContext& g = *ctx;
14839
0
    ImGuiDockContext* dc  = &ctx->DockContext;
14840
14841
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRemoveNode 0x%08X\n", node->ID);
14842
0
    IM_ASSERT(DockContextFindNodeByID(ctx, node->ID) == node);
14843
0
    IM_ASSERT(node->ChildNodes[0] == NULL && node->ChildNodes[1] == NULL);
14844
0
    IM_ASSERT(node->Windows.Size == 0);
14845
14846
0
    if (node->HostWindow)
14847
0
        node->HostWindow->DockNodeAsHost = NULL;
14848
14849
0
    ImGuiDockNode* parent_node = node->ParentNode;
14850
0
    const bool merge = (merge_sibling_into_parent_node && parent_node != NULL);
14851
0
    if (merge)
14852
0
    {
14853
0
        IM_ASSERT(parent_node->ChildNodes[0] == node || parent_node->ChildNodes[1] == node);
14854
0
        ImGuiDockNode* sibling_node = (parent_node->ChildNodes[0] == node ? parent_node->ChildNodes[1] : parent_node->ChildNodes[0]);
14855
0
        DockNodeTreeMerge(&g, parent_node, sibling_node);
14856
0
    }
14857
0
    else
14858
0
    {
14859
0
        for (int n = 0; parent_node && n < IM_ARRAYSIZE(parent_node->ChildNodes); n++)
14860
0
            if (parent_node->ChildNodes[n] == node)
14861
0
                node->ParentNode->ChildNodes[n] = NULL;
14862
0
        dc->Nodes.SetVoidPtr(node->ID, NULL);
14863
0
        IM_DELETE(node);
14864
0
    }
14865
0
}
14866
14867
static int IMGUI_CDECL DockNodeComparerDepthMostFirst(const void* lhs, const void* rhs)
14868
0
{
14869
0
    const ImGuiDockNode* a = *(const ImGuiDockNode* const*)lhs;
14870
0
    const ImGuiDockNode* b = *(const ImGuiDockNode* const*)rhs;
14871
0
    return ImGui::DockNodeGetDepth(b) - ImGui::DockNodeGetDepth(a);
14872
0
}
14873
14874
// Pre C++0x doesn't allow us to use a function-local type (without linkage) as template parameter, so we moved this here.
14875
struct ImGuiDockContextPruneNodeData
14876
{
14877
    int         CountWindows, CountChildWindows, CountChildNodes;
14878
    ImGuiID     RootId;
14879
0
    ImGuiDockContextPruneNodeData() { CountWindows = CountChildWindows = CountChildNodes = 0; RootId = 0; }
14880
};
14881
14882
// Garbage collect unused nodes (run once at init time)
14883
static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx)
14884
0
{
14885
0
    ImGuiContext& g = *ctx;
14886
0
    ImGuiDockContext* dc  = &ctx->DockContext;
14887
0
    IM_ASSERT(g.Windows.Size == 0);
14888
14889
0
    ImPool<ImGuiDockContextPruneNodeData> pool;
14890
0
    pool.Reserve(dc->NodesSettings.Size);
14891
14892
    // Count child nodes and compute RootID
14893
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
14894
0
    {
14895
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
14896
0
        ImGuiDockContextPruneNodeData* parent_data = settings->ParentNodeId ? pool.GetByKey(settings->ParentNodeId) : 0;
14897
0
        pool.GetOrAddByKey(settings->ID)->RootId = parent_data ? parent_data->RootId : settings->ID;
14898
0
        if (settings->ParentNodeId)
14899
0
            pool.GetOrAddByKey(settings->ParentNodeId)->CountChildNodes++;
14900
0
    }
14901
14902
    // Count reference to dock ids from dockspaces
14903
    // We track the 'auto-DockNode <- manual-Window <- manual-DockSpace' in order to avoid 'auto-DockNode' being ditched by DockContextPruneUnusedSettingsNodes()
14904
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
14905
0
    {
14906
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
14907
0
        if (settings->ParentWindowId != 0)
14908
0
            if (ImGuiWindowSettings* window_settings = FindWindowSettings(settings->ParentWindowId))
14909
0
                if (window_settings->DockId)
14910
0
                    if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(window_settings->DockId))
14911
0
                        data->CountChildNodes++;
14912
0
    }
14913
14914
    // Count reference to dock ids from window settings
14915
    // We guard against the possibility of an invalid .ini file (RootID may point to a missing node)
14916
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14917
0
        if (ImGuiID dock_id = settings->DockId)
14918
0
            if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(dock_id))
14919
0
            {
14920
0
                data->CountWindows++;
14921
0
                if (ImGuiDockContextPruneNodeData* data_root = (data->RootId == dock_id) ? data : pool.GetByKey(data->RootId))
14922
0
                    data_root->CountChildWindows++;
14923
0
            }
14924
14925
    // Prune
14926
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
14927
0
    {
14928
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
14929
0
        ImGuiDockContextPruneNodeData* data = pool.GetByKey(settings->ID);
14930
0
        if (data->CountWindows > 1)
14931
0
            continue;
14932
0
        ImGuiDockContextPruneNodeData* data_root = (data->RootId == settings->ID) ? data : pool.GetByKey(data->RootId);
14933
14934
0
        bool remove = false;
14935
0
        remove |= (data->CountWindows == 1 && settings->ParentNodeId == 0 && data->CountChildNodes == 0 && !(settings->Flags & ImGuiDockNodeFlags_CentralNode));  // Floating root node with only 1 window
14936
0
        remove |= (data->CountWindows == 0 && settings->ParentNodeId == 0 && data->CountChildNodes == 0); // Leaf nodes with 0 window
14937
0
        remove |= (data_root->CountChildWindows == 0);
14938
0
        if (remove)
14939
0
        {
14940
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextPruneUnusedSettingsNodes: Prune 0x%08X\n", settings->ID);
14941
0
            DockSettingsRemoveNodeReferences(&settings->ID, 1);
14942
0
            settings->ID = 0;
14943
0
        }
14944
0
    }
14945
0
}
14946
14947
static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count)
14948
0
{
14949
    // Build nodes
14950
0
    for (int node_n = 0; node_n < node_settings_count; node_n++)
14951
0
    {
14952
0
        ImGuiDockNodeSettings* settings = &node_settings_array[node_n];
14953
0
        if (settings->ID == 0)
14954
0
            continue;
14955
0
        ImGuiDockNode* node = DockContextAddNode(ctx, settings->ID);
14956
0
        node->ParentNode = settings->ParentNodeId ? DockContextFindNodeByID(ctx, settings->ParentNodeId) : NULL;
14957
0
        node->Pos = ImVec2(settings->Pos.x, settings->Pos.y);
14958
0
        node->Size = ImVec2(settings->Size.x, settings->Size.y);
14959
0
        node->SizeRef = ImVec2(settings->SizeRef.x, settings->SizeRef.y);
14960
0
        node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_DockNode;
14961
0
        if (node->ParentNode && node->ParentNode->ChildNodes[0] == NULL)
14962
0
            node->ParentNode->ChildNodes[0] = node;
14963
0
        else if (node->ParentNode && node->ParentNode->ChildNodes[1] == NULL)
14964
0
            node->ParentNode->ChildNodes[1] = node;
14965
0
        node->SelectedTabId = settings->SelectedTabId;
14966
0
        node->SplitAxis = (ImGuiAxis)settings->SplitAxis;
14967
0
        node->SetLocalFlags(settings->Flags & ImGuiDockNodeFlags_SavedFlagsMask_);
14968
14969
        // Bind host window immediately if it already exist (in case of a rebuild)
14970
        // This is useful as the RootWindowForTitleBarHighlight links necessary to highlight the currently focused node requires node->HostWindow to be set.
14971
0
        char host_window_title[20];
14972
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
14973
0
        node->HostWindow = FindWindowByName(DockNodeGetHostWindowTitle(root_node, host_window_title, IM_ARRAYSIZE(host_window_title)));
14974
0
    }
14975
0
}
14976
14977
void ImGui::DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id)
14978
0
{
14979
    // Rebind all windows to nodes (they can also lazily rebind but we'll have a visible glitch during the first frame)
14980
0
    ImGuiContext& g = *ctx;
14981
0
    for (int n = 0; n < g.Windows.Size; n++)
14982
0
    {
14983
0
        ImGuiWindow* window = g.Windows[n];
14984
0
        if (window->DockId == 0 || window->LastFrameActive < g.FrameCount - 1)
14985
0
            continue;
14986
0
        if (window->DockNode != NULL)
14987
0
            continue;
14988
14989
0
        ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
14990
0
        IM_ASSERT(node != NULL);   // This should have been called after DockContextBuildNodesFromSettings()
14991
0
        if (root_id == 0 || DockNodeGetRootNode(node)->ID == root_id)
14992
0
            DockNodeAddWindow(node, window, true);
14993
0
    }
14994
0
}
14995
14996
//-----------------------------------------------------------------------------
14997
// Docking: ImGuiDockContext Docking/Undocking functions
14998
//-----------------------------------------------------------------------------
14999
// - DockContextQueueDock()
15000
// - DockContextQueueUndockWindow()
15001
// - DockContextQueueUndockNode()
15002
// - DockContextQueueNotifyRemovedNode()
15003
// - DockContextProcessDock()
15004
// - DockContextProcessUndockWindow()
15005
// - DockContextProcessUndockNode()
15006
// - DockContextCalcDropPosForDocking()
15007
//-----------------------------------------------------------------------------
15008
15009
void ImGui::DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer)
15010
0
{
15011
0
    IM_ASSERT(target != payload);
15012
0
    ImGuiDockRequest req;
15013
0
    req.Type = ImGuiDockRequestType_Dock;
15014
0
    req.DockTargetWindow = target;
15015
0
    req.DockTargetNode = target_node;
15016
0
    req.DockPayload = payload;
15017
0
    req.DockSplitDir = split_dir;
15018
0
    req.DockSplitRatio = split_ratio;
15019
0
    req.DockSplitOuter = split_outer;
15020
0
    ctx->DockContext.Requests.push_back(req);
15021
0
}
15022
15023
void ImGui::DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window)
15024
0
{
15025
0
    ImGuiDockRequest req;
15026
0
    req.Type = ImGuiDockRequestType_Undock;
15027
0
    req.UndockTargetWindow = window;
15028
0
    ctx->DockContext.Requests.push_back(req);
15029
0
}
15030
15031
void ImGui::DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
15032
0
{
15033
0
    ImGuiDockRequest req;
15034
0
    req.Type = ImGuiDockRequestType_Undock;
15035
0
    req.UndockTargetNode = node;
15036
0
    ctx->DockContext.Requests.push_back(req);
15037
0
}
15038
15039
void ImGui::DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node)
15040
0
{
15041
0
    ImGuiDockContext* dc  = &ctx->DockContext;
15042
0
    for (int n = 0; n < dc->Requests.Size; n++)
15043
0
        if (dc->Requests[n].DockTargetNode == node)
15044
0
            dc->Requests[n].Type = ImGuiDockRequestType_None;
15045
0
}
15046
15047
void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req)
15048
0
{
15049
0
    IM_ASSERT((req->Type == ImGuiDockRequestType_Dock && req->DockPayload != NULL) || (req->Type == ImGuiDockRequestType_Split && req->DockPayload == NULL));
15050
0
    IM_ASSERT(req->DockTargetWindow != NULL || req->DockTargetNode != NULL);
15051
15052
0
    ImGuiContext& g = *ctx;
15053
0
    IM_UNUSED(g);
15054
15055
0
    ImGuiWindow* payload_window = req->DockPayload;     // Optional
15056
0
    ImGuiWindow* target_window = req->DockTargetWindow;
15057
0
    ImGuiDockNode* node = req->DockTargetNode;
15058
0
    if (payload_window)
15059
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X target '%s' dock window '%s', split_dir %d\n", node ? node->ID : 0, target_window ? target_window->Name : "NULL", payload_window->Name, req->DockSplitDir);
15060
0
    else
15061
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X, split_dir %d\n", node ? node->ID : 0, req->DockSplitDir);
15062
15063
    // Decide which Tab will be selected at the end of the operation
15064
0
    ImGuiID next_selected_id = 0;
15065
0
    ImGuiDockNode* payload_node = NULL;
15066
0
    if (payload_window)
15067
0
    {
15068
0
        payload_node = payload_window->DockNodeAsHost;
15069
0
        payload_window->DockNodeAsHost = NULL; // Important to clear this as the node will have its life as a child which might be merged/deleted later.
15070
0
        if (payload_node && payload_node->IsLeafNode())
15071
0
            next_selected_id = payload_node->TabBar->NextSelectedTabId ? payload_node->TabBar->NextSelectedTabId : payload_node->TabBar->SelectedTabId;
15072
0
        if (payload_node == NULL)
15073
0
            next_selected_id = payload_window->TabId;
15074
0
    }
15075
15076
    // FIXME-DOCK: When we are trying to dock an existing single-window node into a loose window, transfer Node ID as well
15077
    // When processing an interactive split, usually LastFrameAlive will be < g.FrameCount. But DockBuilder operations can make it ==.
15078
0
    if (node)
15079
0
        IM_ASSERT(node->LastFrameAlive <= g.FrameCount);
15080
0
    if (node && target_window && node == target_window->DockNodeAsHost)
15081
0
        IM_ASSERT(node->Windows.Size > 0 || node->IsSplitNode() || node->IsCentralNode());
15082
15083
    // Create new node and add existing window to it
15084
0
    if (node == NULL)
15085
0
    {
15086
0
        node = DockContextAddNode(ctx, 0);
15087
0
        node->Pos = target_window->Pos;
15088
0
        node->Size = target_window->Size;
15089
0
        if (target_window->DockNodeAsHost == NULL)
15090
0
        {
15091
0
            DockNodeAddWindow(node, target_window, true);
15092
0
            node->TabBar->Tabs[0].Flags &= ~ImGuiTabItemFlags_Unsorted;
15093
0
            target_window->DockIsActive = true;
15094
0
        }
15095
0
    }
15096
15097
0
    ImGuiDir split_dir = req->DockSplitDir;
15098
0
    if (split_dir != ImGuiDir_None)
15099
0
    {
15100
        // Split into two, one side will be our payload node unless we are dropping a loose window
15101
0
        const ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
15102
0
        const int split_inheritor_child_idx = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0; // Current contents will be moved to the opposite side
15103
0
        const float split_ratio = req->DockSplitRatio;
15104
0
        DockNodeTreeSplit(ctx, node, split_axis, split_inheritor_child_idx, split_ratio, payload_node);  // payload_node may be NULL here!
15105
0
        ImGuiDockNode* new_node = node->ChildNodes[split_inheritor_child_idx ^ 1];
15106
0
        new_node->HostWindow = node->HostWindow;
15107
0
        node = new_node;
15108
0
    }
15109
0
    node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
15110
15111
0
    if (node != payload_node)
15112
0
    {
15113
        // Create tab bar before we call DockNodeMoveWindows (which would attempt to move the old tab-bar, which would lead us to payload tabs wrongly appearing before target tabs!)
15114
0
        if (node->Windows.Size > 0 && node->TabBar == NULL)
15115
0
        {
15116
0
            DockNodeAddTabBar(node);
15117
0
            for (int n = 0; n < node->Windows.Size; n++)
15118
0
                TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
15119
0
        }
15120
15121
0
        if (payload_node != NULL)
15122
0
        {
15123
            // Transfer full payload node (with 1+ child windows or child nodes)
15124
0
            if (payload_node->IsSplitNode())
15125
0
            {
15126
0
                if (node->Windows.Size > 0)
15127
0
                {
15128
                    // We can dock a split payload into a node that already has windows _only_ if our payload is a node tree with a single visible node.
15129
                    // In this situation, we move the windows of the target node into the currently visible node of the payload.
15130
                    // This allows us to preserve some of the underlying dock tree settings nicely.
15131
0
                    IM_ASSERT(payload_node->OnlyNodeWithWindows != NULL); // The docking should have been blocked by DockNodePreviewDockSetup() early on and never submitted.
15132
0
                    ImGuiDockNode* visible_node = payload_node->OnlyNodeWithWindows;
15133
0
                    if (visible_node->TabBar)
15134
0
                        IM_ASSERT(visible_node->TabBar->Tabs.Size > 0);
15135
0
                    DockNodeMoveWindows(node, visible_node);
15136
0
                    DockNodeMoveWindows(visible_node, node);
15137
0
                    DockSettingsRenameNodeReferences(node->ID, visible_node->ID);
15138
0
                }
15139
0
                if (node->IsCentralNode())
15140
0
                {
15141
                    // Central node property needs to be moved to a leaf node, pick the last focused one.
15142
                    // FIXME-DOCK: If we had to transfer other flags here, what would the policy be?
15143
0
                    ImGuiDockNode* last_focused_node = DockContextFindNodeByID(ctx, payload_node->LastFocusedNodeId);
15144
0
                    IM_ASSERT(last_focused_node != NULL);
15145
0
                    ImGuiDockNode* last_focused_root_node = DockNodeGetRootNode(last_focused_node);
15146
0
                    IM_ASSERT(last_focused_root_node == DockNodeGetRootNode(payload_node));
15147
0
                    last_focused_node->SetLocalFlags(last_focused_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
15148
0
                    node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_CentralNode);
15149
0
                    last_focused_root_node->CentralNode = last_focused_node;
15150
0
                }
15151
15152
0
                IM_ASSERT(node->Windows.Size == 0);
15153
0
                DockNodeMoveChildNodes(node, payload_node);
15154
0
            }
15155
0
            else
15156
0
            {
15157
0
                const ImGuiID payload_dock_id = payload_node->ID;
15158
0
                DockNodeMoveWindows(node, payload_node);
15159
0
                DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
15160
0
            }
15161
0
            DockContextRemoveNode(ctx, payload_node, true);
15162
0
        }
15163
0
        else if (payload_window)
15164
0
        {
15165
            // Transfer single window
15166
0
            const ImGuiID payload_dock_id = payload_window->DockId;
15167
0
            node->VisibleWindow = payload_window;
15168
0
            DockNodeAddWindow(node, payload_window, true);
15169
0
            if (payload_dock_id != 0)
15170
0
                DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
15171
0
        }
15172
0
    }
15173
0
    else
15174
0
    {
15175
        // When docking a floating single window node we want to reevaluate auto-hiding of the tab bar
15176
0
        node->WantHiddenTabBarUpdate = true;
15177
0
    }
15178
15179
    // Update selection immediately
15180
0
    if (ImGuiTabBar* tab_bar = node->TabBar)
15181
0
        tab_bar->NextSelectedTabId = next_selected_id;
15182
0
    MarkIniSettingsDirty();
15183
0
}
15184
15185
// Problem:
15186
//   Undocking a large (~full screen) window would leave it so large that the bottom right sizing corner would more
15187
//   than likely be off the screen and the window would be hard to resize to fit on screen. This can be particularly problematic
15188
//   with 'ConfigWindowsMoveFromTitleBarOnly=true' and/or with 'ConfigWindowsResizeFromEdges=false' as well (the later can be
15189
//   due to missing ImGuiBackendFlags_HasMouseCursors backend flag).
15190
// Solution:
15191
//   When undocking a window we currently force its maximum size to 90% of the host viewport or monitor.
15192
// Reevaluate this when we implement preserving docked/undocked size ("docking_wip/undocked_size" branch).
15193
static ImVec2 FixLargeWindowsWhenUndocking(const ImVec2& size, ImGuiViewport* ref_viewport)
15194
0
{
15195
0
    if (ref_viewport == NULL)
15196
0
        return size;
15197
15198
0
    ImGuiContext& g = *GImGui;
15199
0
    ImVec2 max_size = ImFloor(ref_viewport->WorkSize * 0.90f);
15200
0
    if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
15201
0
    {
15202
0
        const ImGuiPlatformMonitor* monitor = ImGui::GetViewportPlatformMonitor(ref_viewport);
15203
0
        max_size = ImFloor(monitor->WorkSize * 0.90f);
15204
0
    }
15205
0
    return ImMin(size, max_size);
15206
0
}
15207
15208
void ImGui::DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref)
15209
0
{
15210
0
    ImGuiContext& g = *ctx;
15211
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockWindow window '%s', clear_persistent_docking_ref = %d\n", window->Name, clear_persistent_docking_ref);
15212
0
    if (window->DockNode)
15213
0
        DockNodeRemoveWindow(window->DockNode, window, clear_persistent_docking_ref ? 0 : window->DockId);
15214
0
    else
15215
0
        window->DockId = 0;
15216
0
    window->Collapsed = false;
15217
0
    window->DockIsActive = false;
15218
0
    window->DockNodeIsVisible = window->DockTabIsVisible = false;
15219
0
    window->Size = window->SizeFull = FixLargeWindowsWhenUndocking(window->SizeFull, window->Viewport);
15220
15221
0
    MarkIniSettingsDirty();
15222
0
}
15223
15224
void ImGui::DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
15225
0
{
15226
0
    ImGuiContext& g = *ctx;
15227
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockNode node %08X\n", node->ID);
15228
0
    IM_ASSERT(node->IsLeafNode());
15229
0
    IM_ASSERT(node->Windows.Size >= 1);
15230
15231
0
    if (node->IsRootNode() || node->IsCentralNode())
15232
0
    {
15233
        // In the case of a root node or central node, the node will have to stay in place. Create a new node to receive the payload.
15234
0
        ImGuiDockNode* new_node = DockContextAddNode(ctx, 0);
15235
0
        new_node->Pos = node->Pos;
15236
0
        new_node->Size = node->Size;
15237
0
        new_node->SizeRef = node->SizeRef;
15238
0
        DockNodeMoveWindows(new_node, node);
15239
0
        DockSettingsRenameNodeReferences(node->ID, new_node->ID);
15240
0
        node = new_node;
15241
0
    }
15242
0
    else
15243
0
    {
15244
        // Otherwise extract our node and merge our sibling back into the parent node.
15245
0
        IM_ASSERT(node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
15246
0
        int index_in_parent = (node->ParentNode->ChildNodes[0] == node) ? 0 : 1;
15247
0
        node->ParentNode->ChildNodes[index_in_parent] = NULL;
15248
0
        DockNodeTreeMerge(ctx, node->ParentNode, node->ParentNode->ChildNodes[index_in_parent ^ 1]);
15249
0
        node->ParentNode->AuthorityForViewport = ImGuiDataAuthority_Window; // The node that stays in place keeps the viewport, so our newly dragged out node will create a new viewport
15250
0
        node->ParentNode = NULL;
15251
0
    }
15252
0
    for (int n = 0; n < node->Windows.Size; n++)
15253
0
    {
15254
0
        ImGuiWindow* window = node->Windows[n];
15255
0
        window->Flags &= ~ImGuiWindowFlags_ChildWindow;
15256
0
        if (window->ParentWindow)
15257
0
            window->ParentWindow->DC.ChildWindows.find_erase(window);
15258
0
        UpdateWindowParentAndRootLinks(window, window->Flags, NULL);
15259
0
    }
15260
0
    node->AuthorityForPos = node->AuthorityForSize = ImGuiDataAuthority_DockNode;
15261
0
    node->Size = FixLargeWindowsWhenUndocking(node->Size, node->Windows[0]->Viewport);
15262
0
    node->WantMouseMove = true;
15263
0
    MarkIniSettingsDirty();
15264
0
}
15265
15266
// This is mostly used for automation.
15267
bool ImGui::DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDir split_dir, bool split_outer, ImVec2* out_pos)
15268
0
{
15269
    // In DockNodePreviewDockSetup() for a root central node instead of showing both "inner" and "outer" drop rects
15270
    // (which would be functionally identical) we only show the outer one. Reflect this here.
15271
0
    if (target_node && target_node->ParentNode == NULL && target_node->IsCentralNode() && split_dir != ImGuiDir_None)
15272
0
        split_outer = true;
15273
0
    ImGuiDockPreviewData split_data;
15274
0
    DockNodePreviewDockSetup(target, target_node, payload_window, payload_node, &split_data, false, split_outer);
15275
0
    if (split_data.DropRectsDraw[split_dir+1].IsInverted())
15276
0
        return false;
15277
0
    *out_pos = split_data.DropRectsDraw[split_dir+1].GetCenter();
15278
0
    return true;
15279
0
}
15280
15281
//-----------------------------------------------------------------------------
15282
// Docking: ImGuiDockNode
15283
//-----------------------------------------------------------------------------
15284
// - DockNodeGetTabOrder()
15285
// - DockNodeAddWindow()
15286
// - DockNodeRemoveWindow()
15287
// - DockNodeMoveChildNodes()
15288
// - DockNodeMoveWindows()
15289
// - DockNodeApplyPosSizeToWindows()
15290
// - DockNodeHideHostWindow()
15291
// - ImGuiDockNodeFindInfoResults
15292
// - DockNodeFindInfo()
15293
// - DockNodeFindWindowByID()
15294
// - DockNodeUpdateFlagsAndCollapse()
15295
// - DockNodeUpdateHasCentralNodeFlag()
15296
// - DockNodeUpdateVisibleFlag()
15297
// - DockNodeStartMouseMovingWindow()
15298
// - DockNodeUpdate()
15299
// - DockNodeUpdateWindowMenu()
15300
// - DockNodeBeginAmendTabBar()
15301
// - DockNodeEndAmendTabBar()
15302
// - DockNodeUpdateTabBar()
15303
// - DockNodeAddTabBar()
15304
// - DockNodeRemoveTabBar()
15305
// - DockNodeIsDropAllowedOne()
15306
// - DockNodeIsDropAllowed()
15307
// - DockNodeCalcTabBarLayout()
15308
// - DockNodeCalcSplitRects()
15309
// - DockNodeCalcDropRectsAndTestMousePos()
15310
// - DockNodePreviewDockSetup()
15311
// - DockNodePreviewDockRender()
15312
//-----------------------------------------------------------------------------
15313
15314
ImGuiDockNode::ImGuiDockNode(ImGuiID id)
15315
0
{
15316
0
    ID = id;
15317
0
    SharedFlags = LocalFlags = LocalFlagsInWindows = MergedFlags = ImGuiDockNodeFlags_None;
15318
0
    ParentNode = ChildNodes[0] = ChildNodes[1] = NULL;
15319
0
    TabBar = NULL;
15320
0
    SplitAxis = ImGuiAxis_None;
15321
15322
0
    State = ImGuiDockNodeState_Unknown;
15323
0
    LastBgColor = IM_COL32_WHITE;
15324
0
    HostWindow = VisibleWindow = NULL;
15325
0
    CentralNode = OnlyNodeWithWindows = NULL;
15326
0
    CountNodeWithWindows = 0;
15327
0
    LastFrameAlive = LastFrameActive = LastFrameFocused = -1;
15328
0
    LastFocusedNodeId = 0;
15329
0
    SelectedTabId = 0;
15330
0
    WantCloseTabId = 0;
15331
0
    AuthorityForPos = AuthorityForSize = ImGuiDataAuthority_DockNode;
15332
0
    AuthorityForViewport = ImGuiDataAuthority_Auto;
15333
0
    IsVisible = true;
15334
0
    IsFocused = HasCloseButton = HasWindowMenuButton = HasCentralNodeChild = false;
15335
0
    IsBgDrawnThisFrame = false;
15336
0
    WantCloseAll = WantLockSizeOnce = WantMouseMove = WantHiddenTabBarUpdate = WantHiddenTabBarToggle = false;
15337
0
}
15338
15339
ImGuiDockNode::~ImGuiDockNode()
15340
0
{
15341
0
    IM_DELETE(TabBar);
15342
0
    TabBar = NULL;
15343
0
    ChildNodes[0] = ChildNodes[1] = NULL;
15344
0
}
15345
15346
int ImGui::DockNodeGetTabOrder(ImGuiWindow* window)
15347
0
{
15348
0
    ImGuiTabBar* tab_bar = window->DockNode->TabBar;
15349
0
    if (tab_bar == NULL)
15350
0
        return -1;
15351
0
    ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, window->TabId);
15352
0
    return tab ? TabBarGetTabOrder(tab_bar, tab) : -1;
15353
0
}
15354
15355
static void DockNodeHideWindowDuringHostWindowCreation(ImGuiWindow* window)
15356
0
{
15357
0
    window->Hidden = true;
15358
0
    window->HiddenFramesCanSkipItems = window->Active ? 1 : 2;
15359
0
}
15360
15361
static void ImGui::DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar)
15362
0
{
15363
0
    ImGuiContext& g = *GImGui; (void)g;
15364
0
    if (window->DockNode)
15365
0
    {
15366
        // Can overwrite an existing window->DockNode (e.g. pointing to a disabled DockSpace node)
15367
0
        IM_ASSERT(window->DockNode->ID != node->ID);
15368
0
        DockNodeRemoveWindow(window->DockNode, window, 0);
15369
0
    }
15370
0
    IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL);
15371
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeAddWindow node 0x%08X window '%s'\n", node->ID, window->Name);
15372
15373
    // If more than 2 windows appeared on the same frame leading to the creation of a new hosting window,
15374
    // we'll hide windows until the host window is ready. Hide the 1st window after its been output (so it is not visible for one frame).
15375
    // We will call DockNodeHideWindowDuringHostWindowCreation() on ourselves in Begin()
15376
0
    if (node->HostWindow == NULL && node->Windows.Size == 1 && node->Windows[0]->WasActive == false)
15377
0
        DockNodeHideWindowDuringHostWindowCreation(node->Windows[0]);
15378
15379
0
    node->Windows.push_back(window);
15380
0
    node->WantHiddenTabBarUpdate = true;
15381
0
    window->DockNode = node;
15382
0
    window->DockId = node->ID;
15383
0
    window->DockIsActive = (node->Windows.Size > 1);
15384
0
    window->DockTabWantClose = false;
15385
15386
    // When reactivating a node with one or two loose window, the window pos/size/viewport are authoritative over the node storage.
15387
    // In particular it is important we init the viewport from the first window so we don't create two viewports and drop one.
15388
0
    if (node->HostWindow == NULL && node->IsFloatingNode())
15389
0
    {
15390
0
        if (node->AuthorityForPos == ImGuiDataAuthority_Auto)
15391
0
            node->AuthorityForPos = ImGuiDataAuthority_Window;
15392
0
        if (node->AuthorityForSize == ImGuiDataAuthority_Auto)
15393
0
            node->AuthorityForSize = ImGuiDataAuthority_Window;
15394
0
        if (node->AuthorityForViewport == ImGuiDataAuthority_Auto)
15395
0
            node->AuthorityForViewport = ImGuiDataAuthority_Window;
15396
0
    }
15397
15398
    // Add to tab bar if requested
15399
0
    if (add_to_tab_bar)
15400
0
    {
15401
0
        if (node->TabBar == NULL)
15402
0
        {
15403
0
            DockNodeAddTabBar(node);
15404
0
            node->TabBar->SelectedTabId = node->TabBar->NextSelectedTabId = node->SelectedTabId;
15405
15406
            // Add existing windows
15407
0
            for (int n = 0; n < node->Windows.Size - 1; n++)
15408
0
                TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
15409
0
        }
15410
0
        TabBarAddTab(node->TabBar, ImGuiTabItemFlags_Unsorted, window);
15411
0
    }
15412
15413
0
    DockNodeUpdateVisibleFlag(node);
15414
15415
    // Update this without waiting for the next time we Begin() in the window, so our host window will have the proper title bar color on its first frame.
15416
0
    if (node->HostWindow)
15417
0
        UpdateWindowParentAndRootLinks(window, window->Flags | ImGuiWindowFlags_ChildWindow, node->HostWindow);
15418
0
}
15419
15420
static void ImGui::DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id)
15421
0
{
15422
0
    ImGuiContext& g = *GImGui;
15423
0
    IM_ASSERT(window->DockNode == node);
15424
    //IM_ASSERT(window->RootWindowDockTree == node->HostWindow);
15425
    //IM_ASSERT(window->LastFrameActive < g.FrameCount);    // We may call this from Begin()
15426
0
    IM_ASSERT(save_dock_id == 0 || save_dock_id == node->ID);
15427
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeRemoveWindow node 0x%08X window '%s'\n", node->ID, window->Name);
15428
15429
0
    window->DockNode = NULL;
15430
0
    window->DockIsActive = window->DockTabWantClose = false;
15431
0
    window->DockId = save_dock_id;
15432
0
    window->Flags &= ~ImGuiWindowFlags_ChildWindow;
15433
0
    if (window->ParentWindow)
15434
0
        window->ParentWindow->DC.ChildWindows.find_erase(window);
15435
0
    UpdateWindowParentAndRootLinks(window, window->Flags, NULL); // Update immediately
15436
15437
    // Remove window
15438
0
    bool erased = false;
15439
0
    for (int n = 0; n < node->Windows.Size; n++)
15440
0
        if (node->Windows[n] == window)
15441
0
        {
15442
0
            node->Windows.erase(node->Windows.Data + n);
15443
0
            erased = true;
15444
0
            break;
15445
0
        }
15446
0
    if (!erased)
15447
0
        IM_ASSERT(erased);
15448
0
    if (node->VisibleWindow == window)
15449
0
        node->VisibleWindow = NULL;
15450
15451
    // Remove tab and possibly tab bar
15452
0
    node->WantHiddenTabBarUpdate = true;
15453
0
    if (node->TabBar)
15454
0
    {
15455
0
        TabBarRemoveTab(node->TabBar, window->TabId);
15456
0
        const int tab_count_threshold_for_tab_bar = node->IsCentralNode() ? 1 : 2;
15457
0
        if (node->Windows.Size < tab_count_threshold_for_tab_bar)
15458
0
            DockNodeRemoveTabBar(node);
15459
0
    }
15460
15461
0
    if (node->Windows.Size == 0 && !node->IsCentralNode() && !node->IsDockSpace() && window->DockId != node->ID)
15462
0
    {
15463
        // Automatic dock node delete themselves if they are not holding at least one tab
15464
0
        DockContextRemoveNode(&g, node, true);
15465
0
        return;
15466
0
    }
15467
15468
0
    if (node->Windows.Size == 1 && !node->IsCentralNode() && node->HostWindow)
15469
0
    {
15470
0
        ImGuiWindow* remaining_window = node->Windows[0];
15471
0
        if (node->HostWindow->ViewportOwned && node->IsRootNode())
15472
0
        {
15473
            // Transfer viewport back to the remaining loose window
15474
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Node %08X transfer Viewport %08X=>%08X for Window '%s'\n", node->ID, node->HostWindow->Viewport->ID, remaining_window->ID, remaining_window->Name);
15475
0
            IM_ASSERT(node->HostWindow->Viewport->Window == node->HostWindow);
15476
0
            node->HostWindow->Viewport->Window = remaining_window;
15477
0
            node->HostWindow->Viewport->ID = remaining_window->ID;
15478
0
        }
15479
0
        remaining_window->Collapsed = node->HostWindow->Collapsed;
15480
0
    }
15481
15482
    // Update visibility immediately is required so the DockNodeUpdateRemoveInactiveChilds() processing can reflect changes up the tree
15483
0
    DockNodeUpdateVisibleFlag(node);
15484
0
}
15485
15486
static void ImGui::DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
15487
0
{
15488
0
    IM_ASSERT(dst_node->Windows.Size == 0);
15489
0
    dst_node->ChildNodes[0] = src_node->ChildNodes[0];
15490
0
    dst_node->ChildNodes[1] = src_node->ChildNodes[1];
15491
0
    if (dst_node->ChildNodes[0])
15492
0
        dst_node->ChildNodes[0]->ParentNode = dst_node;
15493
0
    if (dst_node->ChildNodes[1])
15494
0
        dst_node->ChildNodes[1]->ParentNode = dst_node;
15495
0
    dst_node->SplitAxis = src_node->SplitAxis;
15496
0
    dst_node->SizeRef = src_node->SizeRef;
15497
0
    src_node->ChildNodes[0] = src_node->ChildNodes[1] = NULL;
15498
0
}
15499
15500
static void ImGui::DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
15501
0
{
15502
    // Insert tabs in the same orders as currently ordered (node->Windows isn't ordered)
15503
0
    IM_ASSERT(src_node && dst_node && dst_node != src_node);
15504
0
    ImGuiTabBar* src_tab_bar = src_node->TabBar;
15505
0
    if (src_tab_bar != NULL)
15506
0
        IM_ASSERT(src_node->Windows.Size <= src_node->TabBar->Tabs.Size);
15507
15508
    // If the dst_node is empty we can just move the entire tab bar (to preserve selection, scrolling, etc.)
15509
0
    bool move_tab_bar = (src_tab_bar != NULL) && (dst_node->TabBar == NULL);
15510
0
    if (move_tab_bar)
15511
0
    {
15512
0
        dst_node->TabBar = src_node->TabBar;
15513
0
        src_node->TabBar = NULL;
15514
0
    }
15515
15516
    // Tab order is not important here, it is preserved by sorting in DockNodeUpdateTabBar().
15517
0
    for (ImGuiWindow* window : src_node->Windows)
15518
0
    {
15519
0
        window->DockNode = NULL;
15520
0
        window->DockIsActive = false;
15521
0
        DockNodeAddWindow(dst_node, window, !move_tab_bar);
15522
0
    }
15523
0
    src_node->Windows.clear();
15524
15525
0
    if (!move_tab_bar && src_node->TabBar)
15526
0
    {
15527
0
        if (dst_node->TabBar)
15528
0
            dst_node->TabBar->SelectedTabId = src_node->TabBar->SelectedTabId;
15529
0
        DockNodeRemoveTabBar(src_node);
15530
0
    }
15531
0
}
15532
15533
static void ImGui::DockNodeApplyPosSizeToWindows(ImGuiDockNode* node)
15534
0
{
15535
0
    for (int n = 0; n < node->Windows.Size; n++)
15536
0
    {
15537
0
        SetWindowPos(node->Windows[n], node->Pos, ImGuiCond_Always); // We don't assign directly to Pos because it can break the calculation of SizeContents on next frame
15538
0
        SetWindowSize(node->Windows[n], node->Size, ImGuiCond_Always);
15539
0
    }
15540
0
}
15541
15542
static void ImGui::DockNodeHideHostWindow(ImGuiDockNode* node)
15543
0
{
15544
0
    if (node->HostWindow)
15545
0
    {
15546
0
        if (node->HostWindow->DockNodeAsHost == node)
15547
0
            node->HostWindow->DockNodeAsHost = NULL;
15548
0
        node->HostWindow = NULL;
15549
0
    }
15550
15551
0
    if (node->Windows.Size == 1)
15552
0
    {
15553
0
        node->VisibleWindow = node->Windows[0];
15554
0
        node->Windows[0]->DockIsActive = false;
15555
0
    }
15556
15557
0
    if (node->TabBar)
15558
0
        DockNodeRemoveTabBar(node);
15559
0
}
15560
15561
// Search function called once by root node in DockNodeUpdate()
15562
struct ImGuiDockNodeTreeInfo
15563
{
15564
    ImGuiDockNode*      CentralNode;
15565
    ImGuiDockNode*      FirstNodeWithWindows;
15566
    int                 CountNodesWithWindows;
15567
    //ImGuiWindowClass  WindowClassForMerges;
15568
15569
0
    ImGuiDockNodeTreeInfo() { memset(this, 0, sizeof(*this)); }
15570
};
15571
15572
static void DockNodeFindInfo(ImGuiDockNode* node, ImGuiDockNodeTreeInfo* info)
15573
0
{
15574
0
    if (node->Windows.Size > 0)
15575
0
    {
15576
0
        if (info->FirstNodeWithWindows == NULL)
15577
0
            info->FirstNodeWithWindows = node;
15578
0
        info->CountNodesWithWindows++;
15579
0
    }
15580
0
    if (node->IsCentralNode())
15581
0
    {
15582
0
        IM_ASSERT(info->CentralNode == NULL); // Should be only one
15583
0
        IM_ASSERT(node->IsLeafNode() && "If you get this assert: please submit .ini file + repro of actions leading to this.");
15584
0
        info->CentralNode = node;
15585
0
    }
15586
0
    if (info->CountNodesWithWindows > 1 && info->CentralNode != NULL)
15587
0
        return;
15588
0
    if (node->ChildNodes[0])
15589
0
        DockNodeFindInfo(node->ChildNodes[0], info);
15590
0
    if (node->ChildNodes[1])
15591
0
        DockNodeFindInfo(node->ChildNodes[1], info);
15592
0
}
15593
15594
static ImGuiWindow* ImGui::DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id)
15595
0
{
15596
0
    IM_ASSERT(id != 0);
15597
0
    for (int n = 0; n < node->Windows.Size; n++)
15598
0
        if (node->Windows[n]->ID == id)
15599
0
            return node->Windows[n];
15600
0
    return NULL;
15601
0
}
15602
15603
// - Remove inactive windows/nodes.
15604
// - Update visibility flag.
15605
static void ImGui::DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node)
15606
0
{
15607
0
    ImGuiContext& g = *GImGui;
15608
0
    IM_ASSERT(node->ParentNode == NULL || node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
15609
15610
    // Inherit most flags
15611
0
    if (node->ParentNode)
15612
0
        node->SharedFlags = node->ParentNode->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
15613
15614
    // Recurse into children
15615
    // There is the possibility that one of our child becoming empty will delete itself and moving its sibling contents into 'node'.
15616
    // If 'node->ChildNode[0]' delete itself, then 'node->ChildNode[1]->Windows' will be moved into 'node'
15617
    // If 'node->ChildNode[1]' delete itself, then 'node->ChildNode[0]->Windows' will be moved into 'node' and the "remove inactive windows" loop will have run twice on those windows (harmless)
15618
0
    node->HasCentralNodeChild = false;
15619
0
    if (node->ChildNodes[0])
15620
0
        DockNodeUpdateFlagsAndCollapse(node->ChildNodes[0]);
15621
0
    if (node->ChildNodes[1])
15622
0
        DockNodeUpdateFlagsAndCollapse(node->ChildNodes[1]);
15623
15624
    // Remove inactive windows, collapse nodes
15625
    // Merge node flags overrides stored in windows
15626
0
    node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
15627
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
15628
0
    {
15629
0
        ImGuiWindow* window = node->Windows[window_n];
15630
0
        IM_ASSERT(window->DockNode == node);
15631
15632
0
        bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
15633
0
        bool remove = false;
15634
0
        remove |= node_was_active && (window->LastFrameActive + 1 < g.FrameCount);
15635
0
        remove |= node_was_active && (node->WantCloseAll || node->WantCloseTabId == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument);  // Submit all _expected_ closure from last frame
15636
0
        remove |= (window->DockTabWantClose);
15637
0
        if (remove)
15638
0
        {
15639
0
            window->DockTabWantClose = false;
15640
0
            if (node->Windows.Size == 1 && !node->IsCentralNode())
15641
0
            {
15642
0
                DockNodeHideHostWindow(node);
15643
0
                node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
15644
0
                DockNodeRemoveWindow(node, window, node->ID); // Will delete the node so it'll be invalid on return
15645
0
                return;
15646
0
            }
15647
0
            DockNodeRemoveWindow(node, window, node->ID);
15648
0
            window_n--;
15649
0
            continue;
15650
0
        }
15651
15652
        // FIXME-DOCKING: Missing policies for conflict resolution, hence the "Experimental" tag on this.
15653
        //node->LocalFlagsInWindow &= ~window->WindowClass.DockNodeFlagsOverrideClear;
15654
0
        node->LocalFlagsInWindows |= window->WindowClass.DockNodeFlagsOverrideSet;
15655
0
    }
15656
0
    node->UpdateMergedFlags();
15657
15658
    // Auto-hide tab bar option
15659
0
    ImGuiDockNodeFlags node_flags = node->MergedFlags;
15660
0
    if (node->WantHiddenTabBarUpdate && node->Windows.Size == 1 && (node_flags & ImGuiDockNodeFlags_AutoHideTabBar) && !node->IsHiddenTabBar())
15661
0
        node->WantHiddenTabBarToggle = true;
15662
0
    node->WantHiddenTabBarUpdate = false;
15663
15664
    // Cancel toggling if we know our tab bar is enforced to be hidden at all times
15665
0
    if (node->WantHiddenTabBarToggle && node->VisibleWindow && (node->VisibleWindow->WindowClass.DockNodeFlagsOverrideSet & ImGuiDockNodeFlags_HiddenTabBar))
15666
0
        node->WantHiddenTabBarToggle = false;
15667
15668
    // Apply toggles at a single point of the frame (here!)
15669
0
    if (node->Windows.Size > 1)
15670
0
        node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
15671
0
    else if (node->WantHiddenTabBarToggle)
15672
0
        node->SetLocalFlags(node->LocalFlags ^ ImGuiDockNodeFlags_HiddenTabBar);
15673
0
    node->WantHiddenTabBarToggle = false;
15674
15675
0
    DockNodeUpdateVisibleFlag(node);
15676
0
}
15677
15678
// This is rarely called as DockNodeUpdateForRootNode() generally does it most frames.
15679
static void ImGui::DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node)
15680
0
{
15681
0
    node->HasCentralNodeChild = false;
15682
0
    if (node->ChildNodes[0])
15683
0
        DockNodeUpdateHasCentralNodeChild(node->ChildNodes[0]);
15684
0
    if (node->ChildNodes[1])
15685
0
        DockNodeUpdateHasCentralNodeChild(node->ChildNodes[1]);
15686
0
    if (node->IsRootNode())
15687
0
    {
15688
0
        ImGuiDockNode* mark_node = node->CentralNode;
15689
0
        while (mark_node)
15690
0
        {
15691
0
            mark_node->HasCentralNodeChild = true;
15692
0
            mark_node = mark_node->ParentNode;
15693
0
        }
15694
0
    }
15695
0
}
15696
15697
static void ImGui::DockNodeUpdateVisibleFlag(ImGuiDockNode* node)
15698
0
{
15699
    // Update visibility flag
15700
0
    bool is_visible = (node->ParentNode == NULL) ? node->IsDockSpace() : node->IsCentralNode();
15701
0
    is_visible |= (node->Windows.Size > 0);
15702
0
    is_visible |= (node->ChildNodes[0] && node->ChildNodes[0]->IsVisible);
15703
0
    is_visible |= (node->ChildNodes[1] && node->ChildNodes[1]->IsVisible);
15704
0
    node->IsVisible = is_visible;
15705
0
}
15706
15707
static void ImGui::DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window)
15708
0
{
15709
0
    ImGuiContext& g = *GImGui;
15710
0
    IM_ASSERT(node->WantMouseMove == true);
15711
0
    StartMouseMovingWindow(window);
15712
0
    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - node->Pos;
15713
0
    g.MovingWindow = window; // If we are docked into a non moveable root window, StartMouseMovingWindow() won't set g.MovingWindow. Override that decision.
15714
0
    node->WantMouseMove = false;
15715
0
}
15716
15717
// Update CentralNode, OnlyNodeWithWindows, LastFocusedNodeID. Copy window class.
15718
static void ImGui::DockNodeUpdateForRootNode(ImGuiDockNode* node)
15719
0
{
15720
0
    DockNodeUpdateFlagsAndCollapse(node);
15721
15722
    // - Setup central node pointers
15723
    // - Find if there's only a single visible window in the hierarchy (in which case we need to display a regular title bar -> FIXME-DOCK: that last part is not done yet!)
15724
    // Cannot merge this with DockNodeUpdateFlagsAndCollapse() because FirstNodeWithWindows is found after window removal and child collapsing
15725
0
    ImGuiDockNodeTreeInfo info;
15726
0
    DockNodeFindInfo(node, &info);
15727
0
    node->CentralNode = info.CentralNode;
15728
0
    node->OnlyNodeWithWindows = (info.CountNodesWithWindows == 1) ? info.FirstNodeWithWindows : NULL;
15729
0
    node->CountNodeWithWindows = info.CountNodesWithWindows;
15730
0
    if (node->LastFocusedNodeId == 0 && info.FirstNodeWithWindows != NULL)
15731
0
        node->LastFocusedNodeId = info.FirstNodeWithWindows->ID;
15732
15733
    // Copy the window class from of our first window so it can be used for proper dock filtering.
15734
    // When node has mixed windows, prioritize the class with the most constraint (DockingAllowUnclassed = false) as the reference to copy.
15735
    // FIXME-DOCK: We don't recurse properly, this code could be reworked to work from DockNodeUpdateScanRec.
15736
0
    if (ImGuiDockNode* first_node_with_windows = info.FirstNodeWithWindows)
15737
0
    {
15738
0
        node->WindowClass = first_node_with_windows->Windows[0]->WindowClass;
15739
0
        for (int n = 1; n < first_node_with_windows->Windows.Size; n++)
15740
0
            if (first_node_with_windows->Windows[n]->WindowClass.DockingAllowUnclassed == false)
15741
0
            {
15742
0
                node->WindowClass = first_node_with_windows->Windows[n]->WindowClass;
15743
0
                break;
15744
0
            }
15745
0
    }
15746
15747
0
    ImGuiDockNode* mark_node = node->CentralNode;
15748
0
    while (mark_node)
15749
0
    {
15750
0
        mark_node->HasCentralNodeChild = true;
15751
0
        mark_node = mark_node->ParentNode;
15752
0
    }
15753
0
}
15754
15755
static void DockNodeSetupHostWindow(ImGuiDockNode* node, ImGuiWindow* host_window)
15756
0
{
15757
    // Remove ourselves from any previous different host window
15758
    // This can happen if a user mistakenly does (see #4295 for details):
15759
    //  - N+0: DockBuilderAddNode(id, 0)    // missing ImGuiDockNodeFlags_DockSpace
15760
    //  - N+1: NewFrame()                   // will create floating host window for that node
15761
    //  - N+1: DockSpace(id)                // requalify node as dockspace, moving host window
15762
0
    if (node->HostWindow && node->HostWindow != host_window && node->HostWindow->DockNodeAsHost == node)
15763
0
        node->HostWindow->DockNodeAsHost = NULL;
15764
15765
0
    host_window->DockNodeAsHost = node;
15766
0
    node->HostWindow = host_window;
15767
0
}
15768
15769
static void ImGui::DockNodeUpdate(ImGuiDockNode* node)
15770
0
{
15771
0
    ImGuiContext& g = *GImGui;
15772
0
    IM_ASSERT(node->LastFrameActive != g.FrameCount);
15773
0
    node->LastFrameAlive = g.FrameCount;
15774
0
    node->IsBgDrawnThisFrame = false;
15775
15776
0
    node->CentralNode = node->OnlyNodeWithWindows = NULL;
15777
0
    if (node->IsRootNode())
15778
0
        DockNodeUpdateForRootNode(node);
15779
15780
    // Remove tab bar if not needed
15781
0
    if (node->TabBar && node->IsNoTabBar())
15782
0
        DockNodeRemoveTabBar(node);
15783
15784
    // Early out for hidden root dock nodes (when all DockId references are in inactive windows, or there is only 1 floating window holding on the DockId)
15785
0
    bool want_to_hide_host_window = false;
15786
0
    if (node->IsFloatingNode())
15787
0
    {
15788
0
        if (node->Windows.Size <= 1 && node->IsLeafNode())
15789
0
            if (!g.IO.ConfigDockingAlwaysTabBar && (node->Windows.Size == 0 || !node->Windows[0]->WindowClass.DockingAlwaysTabBar))
15790
0
                want_to_hide_host_window = true;
15791
0
        if (node->CountNodeWithWindows == 0)
15792
0
            want_to_hide_host_window = true;
15793
0
    }
15794
0
    if (want_to_hide_host_window)
15795
0
    {
15796
0
        if (node->Windows.Size == 1)
15797
0
        {
15798
            // Floating window pos/size is authoritative
15799
0
            ImGuiWindow* single_window = node->Windows[0];
15800
0
            node->Pos = single_window->Pos;
15801
0
            node->Size = single_window->SizeFull;
15802
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
15803
15804
            // Transfer focus immediately so when we revert to a regular window it is immediately selected
15805
0
            if (node->HostWindow && g.NavWindow == node->HostWindow)
15806
0
                FocusWindow(single_window);
15807
0
            if (node->HostWindow)
15808
0
            {
15809
0
                single_window->Viewport = node->HostWindow->Viewport;
15810
0
                single_window->ViewportId = node->HostWindow->ViewportId;
15811
0
                if (node->HostWindow->ViewportOwned)
15812
0
                {
15813
0
                    single_window->Viewport->Window = single_window;
15814
0
                    single_window->ViewportOwned = true;
15815
0
                }
15816
0
            }
15817
0
        }
15818
15819
0
        DockNodeHideHostWindow(node);
15820
0
        node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
15821
0
        node->WantCloseAll = false;
15822
0
        node->WantCloseTabId = 0;
15823
0
        node->HasCloseButton = node->HasWindowMenuButton = false;
15824
0
        node->LastFrameActive = g.FrameCount;
15825
15826
0
        if (node->WantMouseMove && node->Windows.Size == 1)
15827
0
            DockNodeStartMouseMovingWindow(node, node->Windows[0]);
15828
0
        return;
15829
0
    }
15830
15831
    // In some circumstance we will defer creating the host window (so everything will be kept hidden),
15832
    // while the expected visible window is resizing itself.
15833
    // This is important for first-time (no ini settings restored) single window when io.ConfigDockingAlwaysTabBar is enabled,
15834
    // otherwise the node ends up using the minimum window size. Effectively those windows will take an extra frame to show up:
15835
    //   N+0: Begin(): window created (with no known size), node is created
15836
    //   N+1: DockNodeUpdate(): node skip creating host window / Begin(): window size applied, not visible
15837
    //   N+2: DockNodeUpdate(): node can create host window / Begin(): window becomes visible
15838
    // We could remove this frame if we could reliably calculate the expected window size during node update, before the Begin() code.
15839
    // It would require a generalization of CalcWindowExpectedSize(), probably extracting code away from Begin().
15840
    // In reality it isn't very important as user quickly ends up with size data in .ini file.
15841
0
    if (node->IsVisible && node->HostWindow == NULL && node->IsFloatingNode() && node->IsLeafNode())
15842
0
    {
15843
0
        IM_ASSERT(node->Windows.Size > 0);
15844
0
        ImGuiWindow* ref_window = NULL;
15845
0
        if (node->SelectedTabId != 0) // Note that we prune single-window-node settings on .ini loading, so this is generally 0 for them!
15846
0
            ref_window = DockNodeFindWindowByID(node, node->SelectedTabId);
15847
0
        if (ref_window == NULL)
15848
0
            ref_window = node->Windows[0];
15849
0
        if (ref_window->AutoFitFramesX > 0 || ref_window->AutoFitFramesY > 0)
15850
0
        {
15851
0
            node->State = ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing;
15852
0
            return;
15853
0
        }
15854
0
    }
15855
15856
0
    const ImGuiDockNodeFlags node_flags = node->MergedFlags;
15857
15858
    // Decide if the node will have a close button and a window menu button
15859
0
    node->HasWindowMenuButton = (node->Windows.Size > 0) && (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0;
15860
0
    node->HasCloseButton = false;
15861
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
15862
0
    {
15863
        // FIXME-DOCK: Setting DockIsActive here means that for single active window in a leaf node, DockIsActive will be cleared until the next Begin() call.
15864
0
        ImGuiWindow* window = node->Windows[window_n];
15865
0
        node->HasCloseButton |= window->HasCloseButton;
15866
0
        window->DockIsActive = (node->Windows.Size > 1);
15867
0
    }
15868
0
    if (node_flags & ImGuiDockNodeFlags_NoCloseButton)
15869
0
        node->HasCloseButton = false;
15870
15871
    // Bind or create host window
15872
0
    ImGuiWindow* host_window = NULL;
15873
0
    bool beginned_into_host_window = false;
15874
0
    if (node->IsDockSpace())
15875
0
    {
15876
        // [Explicit root dockspace node]
15877
0
        IM_ASSERT(node->HostWindow);
15878
0
        host_window = node->HostWindow;
15879
0
    }
15880
0
    else
15881
0
    {
15882
        // [Automatic root or child nodes]
15883
0
        if (node->IsRootNode() && node->IsVisible)
15884
0
        {
15885
0
            ImGuiWindow* ref_window = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
15886
15887
            // Sync Pos
15888
0
            if (node->AuthorityForPos == ImGuiDataAuthority_Window && ref_window)
15889
0
                SetNextWindowPos(ref_window->Pos);
15890
0
            else if (node->AuthorityForPos == ImGuiDataAuthority_DockNode)
15891
0
                SetNextWindowPos(node->Pos);
15892
15893
            // Sync Size
15894
0
            if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
15895
0
                SetNextWindowSize(ref_window->SizeFull);
15896
0
            else if (node->AuthorityForSize == ImGuiDataAuthority_DockNode)
15897
0
                SetNextWindowSize(node->Size);
15898
15899
            // Sync Collapsed
15900
0
            if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
15901
0
                SetNextWindowCollapsed(ref_window->Collapsed);
15902
15903
            // Sync Viewport
15904
0
            if (node->AuthorityForViewport == ImGuiDataAuthority_Window && ref_window)
15905
0
                SetNextWindowViewport(ref_window->ViewportId);
15906
15907
0
            SetNextWindowClass(&node->WindowClass);
15908
15909
            // Begin into the host window
15910
0
            char window_label[20];
15911
0
            DockNodeGetHostWindowTitle(node, window_label, IM_ARRAYSIZE(window_label));
15912
0
            ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_DockNodeHost;
15913
0
            window_flags |= ImGuiWindowFlags_NoFocusOnAppearing;
15914
0
            window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoCollapse;
15915
0
            window_flags |= ImGuiWindowFlags_NoTitleBar;
15916
15917
0
            SetNextWindowBgAlpha(0.0f); // Don't set ImGuiWindowFlags_NoBackground because it disables borders
15918
0
            PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));
15919
0
            Begin(window_label, NULL, window_flags);
15920
0
            PopStyleVar();
15921
0
            beginned_into_host_window = true;
15922
15923
0
            host_window = g.CurrentWindow;
15924
0
            DockNodeSetupHostWindow(node, host_window);
15925
0
            host_window->DC.CursorPos = host_window->Pos;
15926
0
            node->Pos = host_window->Pos;
15927
0
            node->Size = host_window->Size;
15928
15929
            // We set ImGuiWindowFlags_NoFocusOnAppearing because we don't want the host window to take full focus (e.g. steal NavWindow)
15930
            // But we still it bring it to the front of display. There's no way to choose this precise behavior via window flags.
15931
            // One simple case to ponder if: window A has a toggle to create windows B/C/D. Dock B/C/D together, clear the toggle and enable it again.
15932
            // When reappearing B/C/D will request focus and be moved to the top of the display pile, but they are not linked to the dock host window
15933
            // during the frame they appear. The dock host window would keep its old display order, and the sorting in EndFrame would move B/C/D back
15934
            // after the dock host window, losing their top-most status.
15935
0
            if (node->HostWindow->Appearing)
15936
0
                BringWindowToDisplayFront(node->HostWindow);
15937
15938
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
15939
0
        }
15940
0
        else if (node->ParentNode)
15941
0
        {
15942
0
            node->HostWindow = host_window = node->ParentNode->HostWindow;
15943
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
15944
0
        }
15945
0
        if (node->WantMouseMove && node->HostWindow)
15946
0
            DockNodeStartMouseMovingWindow(node, node->HostWindow);
15947
0
    }
15948
15949
    // Update focused node (the one whose title bar is highlight) within a node tree
15950
0
    if (node->IsSplitNode())
15951
0
        IM_ASSERT(node->TabBar == NULL);
15952
0
    if (node->IsRootNode())
15953
0
        if (ImGuiWindow* p_window = g.NavWindow ? g.NavWindow->RootWindow : NULL)
15954
0
            while (p_window != NULL && p_window->DockNode != NULL)
15955
0
            {
15956
0
                ImGuiDockNode* p_node = DockNodeGetRootNode(p_window->DockNode);
15957
0
                if (p_node == node)
15958
0
                {
15959
0
                    node->LastFocusedNodeId = p_window->DockNode->ID; // Note: not using root node ID!
15960
0
                    break;
15961
0
                }
15962
0
                p_window = p_node->HostWindow ? p_node->HostWindow->RootWindow : NULL;
15963
0
            }
15964
15965
    // Register a hit-test hole in the window unless we are currently dragging a window that is compatible with our dockspace
15966
0
    ImGuiDockNode* central_node = node->CentralNode;
15967
0
    const bool central_node_hole = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0 && central_node != NULL && central_node->IsEmpty();
15968
0
    bool central_node_hole_register_hit_test_hole = central_node_hole;
15969
0
    if (central_node_hole)
15970
0
        if (const ImGuiPayload* payload = ImGui::GetDragDropPayload())
15971
0
            if (payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && DockNodeIsDropAllowed(host_window, *(ImGuiWindow**)payload->Data))
15972
0
                central_node_hole_register_hit_test_hole = false;
15973
0
    if (central_node_hole_register_hit_test_hole)
15974
0
    {
15975
        // We add a little padding to match the "resize from edges" behavior and allow grabbing the splitter easily.
15976
        // (But we only add it if there's something else on the other side of the hole, otherwise for e.g. fullscreen
15977
        // covering passthru node we'd have a gap on the edge not covered by the hole)
15978
0
        IM_ASSERT(node->IsDockSpace()); // We cannot pass this flag without the DockSpace() api. Testing this because we also setup the hole in host_window->ParentNode
15979
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(central_node);
15980
0
        ImRect root_rect(root_node->Pos, root_node->Pos + root_node->Size);
15981
0
        ImRect hole_rect(central_node->Pos, central_node->Pos + central_node->Size);
15982
0
        if (hole_rect.Min.x > root_rect.Min.x) { hole_rect.Min.x += WINDOWS_HOVER_PADDING; }
15983
0
        if (hole_rect.Max.x < root_rect.Max.x) { hole_rect.Max.x -= WINDOWS_HOVER_PADDING; }
15984
0
        if (hole_rect.Min.y > root_rect.Min.y) { hole_rect.Min.y += WINDOWS_HOVER_PADDING; }
15985
0
        if (hole_rect.Max.y < root_rect.Max.y) { hole_rect.Max.y -= WINDOWS_HOVER_PADDING; }
15986
        //GetForegroundDrawList()->AddRect(hole_rect.Min, hole_rect.Max, IM_COL32(255, 0, 0, 255));
15987
0
        if (central_node_hole && !hole_rect.IsInverted())
15988
0
        {
15989
0
            SetWindowHitTestHole(host_window, hole_rect.Min, hole_rect.Max - hole_rect.Min);
15990
0
            if (host_window->ParentWindow)
15991
0
                SetWindowHitTestHole(host_window->ParentWindow, hole_rect.Min, hole_rect.Max - hole_rect.Min);
15992
0
        }
15993
0
    }
15994
15995
    // Update position/size, process and draw resizing splitters
15996
0
    if (node->IsRootNode() && host_window)
15997
0
    {
15998
0
        DockNodeTreeUpdatePosSize(node, host_window->Pos, host_window->Size);
15999
0
        DockNodeTreeUpdateSplitter(node);
16000
0
    }
16001
16002
    // Draw empty node background (currently can only be the Central Node)
16003
0
    if (host_window && node->IsEmpty() && node->IsVisible)
16004
0
    {
16005
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
16006
0
        node->LastBgColor = (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) ? 0 : GetColorU32(ImGuiCol_DockingEmptyBg);
16007
0
        if (node->LastBgColor != 0)
16008
0
            host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, node->LastBgColor);
16009
0
        node->IsBgDrawnThisFrame = true;
16010
0
    }
16011
16012
    // Draw whole dockspace background if ImGuiDockNodeFlags_PassthruCentralNode if set.
16013
    // We need to draw a background at the root level if requested by ImGuiDockNodeFlags_PassthruCentralNode, but we will only know the correct pos/size
16014
    // _after_ processing the resizing splitters. So we are using the DrawList channel splitting facility to submit drawing primitives out of order!
16015
0
    const bool render_dockspace_bg = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0;
16016
0
    if (render_dockspace_bg && node->IsVisible)
16017
0
    {
16018
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
16019
0
        if (central_node_hole)
16020
0
            RenderRectFilledWithHole(host_window->DrawList, node->Rect(), central_node->Rect(), GetColorU32(ImGuiCol_WindowBg), 0.0f);
16021
0
        else
16022
0
            host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, GetColorU32(ImGuiCol_WindowBg), 0.0f);
16023
0
    }
16024
16025
    // Draw and populate Tab Bar
16026
0
    if (host_window)
16027
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
16028
0
    if (host_window && node->Windows.Size > 0)
16029
0
    {
16030
0
        DockNodeUpdateTabBar(node, host_window);
16031
0
    }
16032
0
    else
16033
0
    {
16034
0
        node->WantCloseAll = false;
16035
0
        node->WantCloseTabId = 0;
16036
0
        node->IsFocused = false;
16037
0
    }
16038
0
    if (node->TabBar && node->TabBar->SelectedTabId)
16039
0
        node->SelectedTabId = node->TabBar->SelectedTabId;
16040
0
    else if (node->Windows.Size > 0)
16041
0
        node->SelectedTabId = node->Windows[0]->TabId;
16042
16043
    // Draw payload drop target
16044
0
    if (host_window && node->IsVisible)
16045
0
        if (node->IsRootNode() && (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != host_window))
16046
0
            BeginDockableDragDropTarget(host_window);
16047
16048
    // We update this after DockNodeUpdateTabBar()
16049
0
    node->LastFrameActive = g.FrameCount;
16050
16051
    // Recurse into children
16052
    // FIXME-DOCK FIXME-OPT: Should not need to recurse into children
16053
0
    if (host_window)
16054
0
    {
16055
0
        if (node->ChildNodes[0])
16056
0
            DockNodeUpdate(node->ChildNodes[0]);
16057
0
        if (node->ChildNodes[1])
16058
0
            DockNodeUpdate(node->ChildNodes[1]);
16059
16060
        // Render outer borders last (after the tab bar)
16061
0
        if (node->IsRootNode())
16062
0
            RenderWindowOuterBorders(host_window);
16063
0
    }
16064
16065
    // End host window
16066
0
    if (beginned_into_host_window) //-V1020
16067
0
        End();
16068
0
}
16069
16070
// Compare TabItem nodes given the last known DockOrder (will persist in .ini file as hint), used to sort tabs when multiple tabs are added on the same frame.
16071
static int IMGUI_CDECL TabItemComparerByDockOrder(const void* lhs, const void* rhs)
16072
0
{
16073
0
    ImGuiWindow* a = ((const ImGuiTabItem*)lhs)->Window;
16074
0
    ImGuiWindow* b = ((const ImGuiTabItem*)rhs)->Window;
16075
0
    if (int d = ((a->DockOrder == -1) ? INT_MAX : a->DockOrder) - ((b->DockOrder == -1) ? INT_MAX : b->DockOrder))
16076
0
        return d;
16077
0
    return (a->BeginOrderWithinContext - b->BeginOrderWithinContext);
16078
0
}
16079
16080
static ImGuiID ImGui::DockNodeUpdateWindowMenu(ImGuiDockNode* node, ImGuiTabBar* tab_bar)
16081
0
{
16082
    // Try to position the menu so it is more likely to stays within the same viewport
16083
0
    ImGuiContext& g = *GImGui;
16084
0
    ImGuiID ret_tab_id = 0;
16085
0
    if (g.Style.WindowMenuButtonPosition == ImGuiDir_Left)
16086
0
        SetNextWindowPos(ImVec2(node->Pos.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(0.0f, 0.0f));
16087
0
    else
16088
0
        SetNextWindowPos(ImVec2(node->Pos.x + node->Size.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(1.0f, 0.0f));
16089
0
    if (BeginPopup("#WindowMenu"))
16090
0
    {
16091
0
        node->IsFocused = true;
16092
0
        if (tab_bar->Tabs.Size == 1)
16093
0
        {
16094
0
            if (MenuItem(LocalizeGetMsg(ImGuiLocKey_DockingHideTabBar), NULL, node->IsHiddenTabBar()))
16095
0
                node->WantHiddenTabBarToggle = true;
16096
0
        }
16097
0
        else
16098
0
        {
16099
0
            for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
16100
0
            {
16101
0
                ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
16102
0
                if (tab->Flags & ImGuiTabItemFlags_Button)
16103
0
                    continue;
16104
0
                if (Selectable(TabBarGetTabName(tab_bar, tab), tab->ID == tab_bar->SelectedTabId))
16105
0
                    ret_tab_id = tab->ID;
16106
0
                SameLine();
16107
0
                Text("   ");
16108
0
            }
16109
0
        }
16110
0
        EndPopup();
16111
0
    }
16112
0
    return ret_tab_id;
16113
0
}
16114
16115
// User helper to append/amend into a dock node tab bar. Most commonly used to add e.g. a "+" button.
16116
bool ImGui::DockNodeBeginAmendTabBar(ImGuiDockNode* node)
16117
0
{
16118
0
    if (node->TabBar == NULL || node->HostWindow == NULL)
16119
0
        return false;
16120
0
    if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
16121
0
        return false;
16122
0
    Begin(node->HostWindow->Name);
16123
0
    PushOverrideID(node->ID);
16124
0
    bool ret = BeginTabBarEx(node->TabBar, node->TabBar->BarRect, node->TabBar->Flags, node);
16125
0
    IM_UNUSED(ret);
16126
0
    IM_ASSERT(ret);
16127
0
    return true;
16128
0
}
16129
16130
void ImGui::DockNodeEndAmendTabBar()
16131
0
{
16132
0
    EndTabBar();
16133
0
    PopID();
16134
0
    End();
16135
0
}
16136
16137
static bool IsDockNodeTitleBarHighlighted(ImGuiDockNode* node, ImGuiDockNode* root_node)
16138
0
{
16139
    // CTRL+Tab highlight (only highlighting leaf node, not whole hierarchy)
16140
0
    ImGuiContext& g = *GImGui;
16141
0
    if (g.NavWindowingTarget)
16142
0
        return (g.NavWindowingTarget->DockNode == node);
16143
16144
    // FIXME-DOCKING: May want alternative to treat central node void differently? e.g. if (g.NavWindow == host_window)
16145
0
    if (g.NavWindow && root_node->LastFocusedNodeId == node->ID)
16146
0
    {
16147
        // FIXME: This could all be backed in RootWindowForTitleBarHighlight? Probably need to reorganize for both dock nodes + other RootWindowForTitleBarHighlight users (not-node)
16148
0
        ImGuiWindow* parent_window = g.NavWindow->RootWindow;
16149
0
        while (parent_window->Flags & ImGuiWindowFlags_ChildMenu)
16150
0
            parent_window = parent_window->ParentWindow->RootWindow;
16151
0
        ImGuiDockNode* start_parent_node = parent_window->DockNodeAsHost ? parent_window->DockNodeAsHost : parent_window->DockNode;
16152
0
        for (ImGuiDockNode* parent_node = start_parent_node; parent_node != NULL; parent_node = parent_node->HostWindow ? parent_node->HostWindow->RootWindow->DockNode : NULL)
16153
0
            if ((parent_node = ImGui::DockNodeGetRootNode(parent_node)) == root_node)
16154
0
                return true;
16155
0
    }
16156
0
    return false;
16157
0
}
16158
16159
// Submit the tab bar corresponding to a dock node and various housekeeping details.
16160
static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window)
16161
0
{
16162
0
    ImGuiContext& g = *GImGui;
16163
0
    ImGuiStyle& style = g.Style;
16164
16165
0
    const bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
16166
0
    const bool closed_all = node->WantCloseAll && node_was_active;
16167
0
    const ImGuiID closed_one = node->WantCloseTabId && node_was_active;
16168
0
    node->WantCloseAll = false;
16169
0
    node->WantCloseTabId = 0;
16170
16171
    // Decide if we should use a focused title bar color
16172
0
    bool is_focused = false;
16173
0
    ImGuiDockNode* root_node = DockNodeGetRootNode(node);
16174
0
    if (IsDockNodeTitleBarHighlighted(node, root_node))
16175
0
        is_focused = true;
16176
16177
    // Hidden tab bar will show a triangle on the upper-left (in Begin)
16178
0
    if (node->IsHiddenTabBar() || node->IsNoTabBar())
16179
0
    {
16180
0
        node->VisibleWindow = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
16181
0
        node->IsFocused = is_focused;
16182
0
        if (is_focused)
16183
0
            node->LastFrameFocused = g.FrameCount;
16184
0
        if (node->VisibleWindow)
16185
0
        {
16186
            // Notify root of visible window (used to display title in OS task bar)
16187
0
            if (is_focused || root_node->VisibleWindow == NULL)
16188
0
                root_node->VisibleWindow = node->VisibleWindow;
16189
0
            if (node->TabBar)
16190
0
                node->TabBar->VisibleTabId = node->VisibleWindow->TabId;
16191
0
        }
16192
0
        return;
16193
0
    }
16194
16195
    // Move ourselves to the Menu layer (so we can be accessed by tapping Alt) + undo SkipItems flag in order to draw over the title bar even if the window is collapsed
16196
0
    bool backup_skip_item = host_window->SkipItems;
16197
0
    if (!node->IsDockSpace())
16198
0
    {
16199
0
        host_window->SkipItems = false;
16200
0
        host_window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
16201
0
    }
16202
16203
    // Use PushOverrideID() instead of PushID() to use the node id _without_ the host window ID.
16204
    // This is to facilitate computing those ID from the outside, and will affect more or less only the ID of the collapse button, popup and tabs,
16205
    // as docked windows themselves will override the stack with their own root ID.
16206
0
    PushOverrideID(node->ID);
16207
0
    ImGuiTabBar* tab_bar = node->TabBar;
16208
0
    bool tab_bar_is_recreated = (tab_bar == NULL); // Tab bar are automatically destroyed when a node gets hidden
16209
0
    if (tab_bar == NULL)
16210
0
    {
16211
0
        DockNodeAddTabBar(node);
16212
0
        tab_bar = node->TabBar;
16213
0
    }
16214
16215
0
    ImGuiID focus_tab_id = 0;
16216
0
    node->IsFocused = is_focused;
16217
16218
0
    const ImGuiDockNodeFlags node_flags = node->MergedFlags;
16219
0
    const bool has_window_menu_button = (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0 && (style.WindowMenuButtonPosition != ImGuiDir_None);
16220
16221
    // In a dock node, the Collapse Button turns into the Window Menu button.
16222
    // FIXME-DOCK FIXME-OPT: Could we recycle popups id across multiple dock nodes?
16223
0
    if (has_window_menu_button && IsPopupOpen("#WindowMenu"))
16224
0
    {
16225
0
        if (ImGuiID tab_id = DockNodeUpdateWindowMenu(node, tab_bar))
16226
0
            focus_tab_id = tab_bar->NextSelectedTabId = tab_id;
16227
0
        is_focused |= node->IsFocused;
16228
0
    }
16229
16230
    // Layout
16231
0
    ImRect title_bar_rect, tab_bar_rect;
16232
0
    ImVec2 window_menu_button_pos;
16233
0
    ImVec2 close_button_pos;
16234
0
    DockNodeCalcTabBarLayout(node, &title_bar_rect, &tab_bar_rect, &window_menu_button_pos, &close_button_pos);
16235
16236
    // Submit new tabs, they will be added as Unsorted and sorted below based on relative DockOrder value.
16237
0
    const int tabs_count_old = tab_bar->Tabs.Size;
16238
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
16239
0
    {
16240
0
        ImGuiWindow* window = node->Windows[window_n];
16241
0
        if (TabBarFindTabByID(tab_bar, window->TabId) == NULL)
16242
0
            TabBarAddTab(tab_bar, ImGuiTabItemFlags_Unsorted, window);
16243
0
    }
16244
16245
    // Title bar
16246
0
    if (is_focused)
16247
0
        node->LastFrameFocused = g.FrameCount;
16248
0
    ImU32 title_bar_col = GetColorU32(host_window->Collapsed ? ImGuiCol_TitleBgCollapsed : is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
16249
0
    ImDrawFlags rounding_flags = CalcRoundingFlagsForRectInRect(title_bar_rect, host_window->Rect(), DOCKING_SPLITTER_SIZE);
16250
0
    host_window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, host_window->WindowRounding, rounding_flags);
16251
16252
    // Docking/Collapse button
16253
0
    if (has_window_menu_button)
16254
0
    {
16255
0
        if (CollapseButton(host_window->GetID("#COLLAPSE"), window_menu_button_pos, node)) // == DockNodeGetWindowMenuButtonId(node)
16256
0
            OpenPopup("#WindowMenu");
16257
0
        if (IsItemActive())
16258
0
            focus_tab_id = tab_bar->SelectedTabId;
16259
0
    }
16260
16261
    // If multiple tabs are appearing on the same frame, sort them based on their persistent DockOrder value
16262
0
    int tabs_unsorted_start = tab_bar->Tabs.Size;
16263
0
    for (int tab_n = tab_bar->Tabs.Size - 1; tab_n >= 0 && (tab_bar->Tabs[tab_n].Flags & ImGuiTabItemFlags_Unsorted); tab_n--)
16264
0
    {
16265
        // FIXME-DOCK: Consider only clearing the flag after the tab has been alive for a few consecutive frames, allowing late comers to not break sorting?
16266
0
        tab_bar->Tabs[tab_n].Flags &= ~ImGuiTabItemFlags_Unsorted;
16267
0
        tabs_unsorted_start = tab_n;
16268
0
    }
16269
0
    if (tab_bar->Tabs.Size > tabs_unsorted_start)
16270
0
    {
16271
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] In node 0x%08X: %d new appearing tabs:%s\n", node->ID, tab_bar->Tabs.Size - tabs_unsorted_start, (tab_bar->Tabs.Size > tabs_unsorted_start + 1) ? " (will sort)" : "");
16272
0
        for (int tab_n = tabs_unsorted_start; tab_n < tab_bar->Tabs.Size; tab_n++)
16273
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] - Tab '%s' Order %d\n", tab_bar->Tabs[tab_n].Window->Name, tab_bar->Tabs[tab_n].Window->DockOrder);
16274
0
        if (tab_bar->Tabs.Size > tabs_unsorted_start + 1)
16275
0
            ImQsort(tab_bar->Tabs.Data + tabs_unsorted_start, tab_bar->Tabs.Size - tabs_unsorted_start, sizeof(ImGuiTabItem), TabItemComparerByDockOrder);
16276
0
    }
16277
16278
    // Apply NavWindow focus back to the tab bar
16279
0
    if (g.NavWindow && g.NavWindow->RootWindow->DockNode == node)
16280
0
        tab_bar->SelectedTabId = g.NavWindow->RootWindow->TabId;
16281
16282
    // Selected newly added tabs, or persistent tab ID if the tab bar was just recreated
16283
0
    if (tab_bar_is_recreated && TabBarFindTabByID(tab_bar, node->SelectedTabId) != NULL)
16284
0
        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = node->SelectedTabId;
16285
0
    else if (tab_bar->Tabs.Size > tabs_count_old)
16286
0
        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = tab_bar->Tabs.back().Window->TabId;
16287
16288
    // Begin tab bar
16289
0
    ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_AutoSelectNewTabs; // | ImGuiTabBarFlags_NoTabListScrollingButtons);
16290
0
    tab_bar_flags |= ImGuiTabBarFlags_SaveSettings | ImGuiTabBarFlags_DockNode;
16291
0
    if (!host_window->Collapsed && is_focused)
16292
0
        tab_bar_flags |= ImGuiTabBarFlags_IsFocused;
16293
0
    BeginTabBarEx(tab_bar, tab_bar_rect, tab_bar_flags, node);
16294
    //host_window->DrawList->AddRect(tab_bar_rect.Min, tab_bar_rect.Max, IM_COL32(255,0,255,255));
16295
16296
    // Backup style colors
16297
0
    ImVec4 backup_style_cols[ImGuiWindowDockStyleCol_COUNT];
16298
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
16299
0
        backup_style_cols[color_n] = g.Style.Colors[GWindowDockStyleColors[color_n]];
16300
16301
    // Submit actual tabs
16302
0
    node->VisibleWindow = NULL;
16303
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
16304
0
    {
16305
0
        ImGuiWindow* window = node->Windows[window_n];
16306
0
        if ((closed_all || closed_one == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument))
16307
0
            continue;
16308
0
        if (window->LastFrameActive + 1 >= g.FrameCount || !node_was_active)
16309
0
        {
16310
0
            ImGuiTabItemFlags tab_item_flags = 0;
16311
0
            tab_item_flags |= window->WindowClass.TabItemFlagsOverrideSet;
16312
0
            if (window->Flags & ImGuiWindowFlags_UnsavedDocument)
16313
0
                tab_item_flags |= ImGuiTabItemFlags_UnsavedDocument;
16314
0
            if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)
16315
0
                tab_item_flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;
16316
16317
            // Apply stored style overrides for the window
16318
0
            for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
16319
0
                g.Style.Colors[GWindowDockStyleColors[color_n]] = ColorConvertU32ToFloat4(window->DockStyle.Colors[color_n]);
16320
16321
            // Note that TabItemEx() calls TabBarCalcTabID() so our tab item ID will ignore the current ID stack (rightly so)
16322
0
            bool tab_open = true;
16323
0
            TabItemEx(tab_bar, window->Name, window->HasCloseButton ? &tab_open : NULL, tab_item_flags, window);
16324
0
            if (!tab_open)
16325
0
                node->WantCloseTabId = window->TabId;
16326
0
            if (tab_bar->VisibleTabId == window->TabId)
16327
0
                node->VisibleWindow = window;
16328
16329
            // Store last item data so it can be queried with IsItemXXX functions after the user Begin() call
16330
0
            window->DockTabItemStatusFlags = g.LastItemData.StatusFlags;
16331
0
            window->DockTabItemRect = g.LastItemData.Rect;
16332
16333
            // Update navigation ID on menu layer
16334
0
            if (g.NavWindow && g.NavWindow->RootWindow == window && (window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0)
16335
0
                host_window->NavLastIds[1] = window->TabId;
16336
0
        }
16337
0
    }
16338
16339
    // Restore style colors
16340
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
16341
0
        g.Style.Colors[GWindowDockStyleColors[color_n]] = backup_style_cols[color_n];
16342
16343
    // Notify root of visible window (used to display title in OS task bar)
16344
0
    if (node->VisibleWindow)
16345
0
        if (is_focused || root_node->VisibleWindow == NULL)
16346
0
            root_node->VisibleWindow = node->VisibleWindow;
16347
16348
    // Close button (after VisibleWindow was updated)
16349
    // Note that VisibleWindow may have been overrided by CTRL+Tabbing, so VisibleWindow->TabId may be != from tab_bar->SelectedTabId
16350
0
    const bool close_button_is_enabled = node->HasCloseButton && node->VisibleWindow && node->VisibleWindow->HasCloseButton;
16351
0
    const bool close_button_is_visible = node->HasCloseButton;
16352
    //const bool close_button_is_visible = close_button_is_enabled; // Most people would expect this behavior of not even showing the button (leaving a hole since we can't claim that space as other windows in the tba bar have one)
16353
0
    if (close_button_is_visible)
16354
0
    {
16355
0
        if (!close_button_is_enabled)
16356
0
        {
16357
0
            PushItemFlag(ImGuiItemFlags_Disabled, true);
16358
0
            PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_Text] * ImVec4(1.0f,1.0f,1.0f,0.4f));
16359
0
        }
16360
0
        if (CloseButton(host_window->GetID("#CLOSE"), close_button_pos))
16361
0
        {
16362
0
            node->WantCloseAll = true;
16363
0
            for (int n = 0; n < tab_bar->Tabs.Size; n++)
16364
0
                TabBarCloseTab(tab_bar, &tab_bar->Tabs[n]);
16365
0
        }
16366
        //if (IsItemActive())
16367
        //    focus_tab_id = tab_bar->SelectedTabId;
16368
0
        if (!close_button_is_enabled)
16369
0
        {
16370
0
            PopStyleColor();
16371
0
            PopItemFlag();
16372
0
        }
16373
0
    }
16374
16375
    // When clicking on the title bar outside of tabs, we still focus the selected tab for that node
16376
    // FIXME: TabItem use AllowItemOverlap so we manually perform a more specific test for now (hovered || held)
16377
0
    ImGuiID title_bar_id = host_window->GetID("#TITLEBAR");
16378
0
    if (g.HoveredId == 0 || g.HoveredId == title_bar_id || g.ActiveId == title_bar_id)
16379
0
    {
16380
0
        bool held;
16381
0
        ButtonBehavior(title_bar_rect, title_bar_id, NULL, &held, ImGuiButtonFlags_AllowItemOverlap);
16382
0
        if (g.HoveredId == title_bar_id)
16383
0
        {
16384
            // ImGuiButtonFlags_AllowItemOverlap + SetItemAllowOverlap() required for appending into dock node tab bar,
16385
            // otherwise dragging window will steal HoveredId and amended tabs cannot get them.
16386
0
            g.LastItemData.ID = title_bar_id;
16387
0
            SetItemAllowOverlap();
16388
0
        }
16389
0
        if (held)
16390
0
        {
16391
0
            if (IsMouseClicked(0))
16392
0
                focus_tab_id = tab_bar->SelectedTabId;
16393
16394
            // Forward moving request to selected window
16395
0
            if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId))
16396
0
                StartMouseMovingWindowOrNode(tab->Window ? tab->Window : node->HostWindow, node, false);
16397
0
        }
16398
0
    }
16399
16400
    // Forward focus from host node to selected window
16401
    //if (is_focused && g.NavWindow == host_window && !g.NavWindowingTarget)
16402
    //    focus_tab_id = tab_bar->SelectedTabId;
16403
16404
    // When clicked on a tab we requested focus to the docked child
16405
    // This overrides the value set by "forward focus from host node to selected window".
16406
0
    if (tab_bar->NextSelectedTabId)
16407
0
        focus_tab_id = tab_bar->NextSelectedTabId;
16408
16409
    // Apply navigation focus
16410
0
    if (focus_tab_id != 0)
16411
0
        if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, focus_tab_id))
16412
0
            if (tab->Window)
16413
0
            {
16414
0
                FocusWindow(tab->Window);
16415
0
                NavInitWindow(tab->Window, false);
16416
0
            }
16417
16418
0
    EndTabBar();
16419
0
    PopID();
16420
16421
    // Restore SkipItems flag
16422
0
    if (!node->IsDockSpace())
16423
0
    {
16424
0
        host_window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
16425
0
        host_window->SkipItems = backup_skip_item;
16426
0
    }
16427
0
}
16428
16429
static void ImGui::DockNodeAddTabBar(ImGuiDockNode* node)
16430
0
{
16431
0
    IM_ASSERT(node->TabBar == NULL);
16432
0
    node->TabBar = IM_NEW(ImGuiTabBar);
16433
0
}
16434
16435
static void ImGui::DockNodeRemoveTabBar(ImGuiDockNode* node)
16436
0
{
16437
0
    if (node->TabBar == NULL)
16438
0
        return;
16439
0
    IM_DELETE(node->TabBar);
16440
0
    node->TabBar = NULL;
16441
0
}
16442
16443
static bool DockNodeIsDropAllowedOne(ImGuiWindow* payload, ImGuiWindow* host_window)
16444
0
{
16445
0
    if (host_window->DockNodeAsHost && host_window->DockNodeAsHost->IsDockSpace() && payload->BeginOrderWithinContext < host_window->BeginOrderWithinContext)
16446
0
        return false;
16447
16448
0
    ImGuiWindowClass* host_class = host_window->DockNodeAsHost ? &host_window->DockNodeAsHost->WindowClass : &host_window->WindowClass;
16449
0
    ImGuiWindowClass* payload_class = &payload->WindowClass;
16450
0
    if (host_class->ClassId != payload_class->ClassId)
16451
0
    {
16452
0
        if (host_class->ClassId != 0 && host_class->DockingAllowUnclassed && payload_class->ClassId == 0)
16453
0
            return true;
16454
0
        if (payload_class->ClassId != 0 && payload_class->DockingAllowUnclassed && host_class->ClassId == 0)
16455
0
            return true;
16456
0
        return false;
16457
0
    }
16458
16459
    // Prevent docking any window created above a popup
16460
    // Technically we should support it (e.g. in the case of a long-lived modal window that had fancy docking features),
16461
    // by e.g. adding a 'if (!ImGui::IsWindowWithinBeginStackOf(host_window, popup_window))' test.
16462
    // But it would requires more work on our end because the dock host windows is technically created in NewFrame()
16463
    // and our ->ParentXXX and ->RootXXX pointers inside windows are currently mislading or lacking.
16464
0
    ImGuiContext& g = *GImGui;
16465
0
    for (int i = g.OpenPopupStack.Size - 1; i >= 0; i--)
16466
0
        if (ImGuiWindow* popup_window = g.OpenPopupStack[i].Window)
16467
0
            if (ImGui::IsWindowWithinBeginStackOf(payload, popup_window))   // Payload is created from within a popup begin stack.
16468
0
                return false;
16469
16470
0
    return true;
16471
0
}
16472
16473
static bool ImGui::DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* root_payload)
16474
0
{
16475
0
    if (root_payload->DockNodeAsHost && root_payload->DockNodeAsHost->IsSplitNode()) // FIXME-DOCK: Missing filtering
16476
0
        return true;
16477
16478
0
    const int payload_count = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows.Size : 1;
16479
0
    for (int payload_n = 0; payload_n < payload_count; payload_n++)
16480
0
    {
16481
0
        ImGuiWindow* payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows[payload_n] : root_payload;
16482
0
        if (DockNodeIsDropAllowedOne(payload, host_window))
16483
0
            return true;
16484
0
    }
16485
0
    return false;
16486
0
}
16487
16488
// window menu button == collapse button when not in a dock node.
16489
// FIXME: This is similar to RenderWindowTitleBarContents(), may want to share code.
16490
static void ImGui::DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos)
16491
0
{
16492
0
    ImGuiContext& g = *GImGui;
16493
0
    ImGuiStyle& style = g.Style;
16494
16495
0
    ImRect r = ImRect(node->Pos.x, node->Pos.y, node->Pos.x + node->Size.x, node->Pos.y + g.FontSize + g.Style.FramePadding.y * 2.0f);
16496
0
    if (out_title_rect) { *out_title_rect = r; }
16497
16498
0
    r.Min.x += style.WindowBorderSize;
16499
0
    r.Max.x -= style.WindowBorderSize;
16500
16501
0
    float button_sz = g.FontSize;
16502
16503
0
    ImVec2 window_menu_button_pos = r.Min;
16504
0
    r.Min.x += style.FramePadding.x;
16505
0
    r.Max.x -= style.FramePadding.x;
16506
0
    if (node->HasCloseButton)
16507
0
    {
16508
0
        r.Max.x -= button_sz;
16509
0
        if (out_close_button_pos) *out_close_button_pos = ImVec2(r.Max.x - style.FramePadding.x, r.Min.y);
16510
0
    }
16511
0
    if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Left)
16512
0
    {
16513
0
        r.Min.x += button_sz + style.ItemInnerSpacing.x;
16514
0
    }
16515
0
    else if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Right)
16516
0
    {
16517
0
        r.Max.x -= button_sz + style.FramePadding.x;
16518
0
        window_menu_button_pos = ImVec2(r.Max.x, r.Min.y);
16519
0
    }
16520
0
    if (out_tab_bar_rect) { *out_tab_bar_rect = r; }
16521
0
    if (out_window_menu_button_pos) { *out_window_menu_button_pos = window_menu_button_pos; }
16522
0
}
16523
16524
void ImGui::DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired)
16525
0
{
16526
0
    ImGuiContext& g = *GImGui;
16527
0
    const float dock_spacing = g.Style.ItemInnerSpacing.x;
16528
0
    const ImGuiAxis axis = (dir == ImGuiDir_Left || dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
16529
0
    pos_new[axis ^ 1] = pos_old[axis ^ 1];
16530
0
    size_new[axis ^ 1] = size_old[axis ^ 1];
16531
16532
    // Distribute size on given axis (with a desired size or equally)
16533
0
    const float w_avail = size_old[axis] - dock_spacing;
16534
0
    if (size_new_desired[axis] > 0.0f && size_new_desired[axis] <= w_avail * 0.5f)
16535
0
    {
16536
0
        size_new[axis] = size_new_desired[axis];
16537
0
        size_old[axis] = IM_FLOOR(w_avail - size_new[axis]);
16538
0
    }
16539
0
    else
16540
0
    {
16541
0
        size_new[axis] = IM_FLOOR(w_avail * 0.5f);
16542
0
        size_old[axis] = IM_FLOOR(w_avail - size_new[axis]);
16543
0
    }
16544
16545
    // Position each node
16546
0
    if (dir == ImGuiDir_Right || dir == ImGuiDir_Down)
16547
0
    {
16548
0
        pos_new[axis] = pos_old[axis] + size_old[axis] + dock_spacing;
16549
0
    }
16550
0
    else if (dir == ImGuiDir_Left || dir == ImGuiDir_Up)
16551
0
    {
16552
0
        pos_new[axis] = pos_old[axis];
16553
0
        pos_old[axis] = pos_new[axis] + size_new[axis] + dock_spacing;
16554
0
    }
16555
0
}
16556
16557
// Retrieve the drop rectangles for a given direction or for the center + perform hit testing.
16558
bool ImGui::DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_r, bool outer_docking, ImVec2* test_mouse_pos)
16559
0
{
16560
0
    ImGuiContext& g = *GImGui;
16561
16562
0
    const float parent_smaller_axis = ImMin(parent.GetWidth(), parent.GetHeight());
16563
0
    const float hs_for_central_nodes = ImMin(g.FontSize * 1.5f, ImMax(g.FontSize * 0.5f, parent_smaller_axis / 8.0f));
16564
0
    float hs_w; // Half-size, longer axis
16565
0
    float hs_h; // Half-size, smaller axis
16566
0
    ImVec2 off; // Distance from edge or center
16567
0
    if (outer_docking)
16568
0
    {
16569
        //hs_w = ImFloor(ImClamp(parent_smaller_axis - hs_for_central_nodes * 4.0f, g.FontSize * 0.5f, g.FontSize * 8.0f));
16570
        //hs_h = ImFloor(hs_w * 0.15f);
16571
        //off = ImVec2(ImFloor(parent.GetWidth() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h), ImFloor(parent.GetHeight() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h));
16572
0
        hs_w = ImFloor(hs_for_central_nodes * 1.50f);
16573
0
        hs_h = ImFloor(hs_for_central_nodes * 0.80f);
16574
0
        off = ImVec2(ImFloor(parent.GetWidth() * 0.5f - hs_h), ImFloor(parent.GetHeight() * 0.5f - hs_h));
16575
0
    }
16576
0
    else
16577
0
    {
16578
0
        hs_w = ImFloor(hs_for_central_nodes);
16579
0
        hs_h = ImFloor(hs_for_central_nodes * 0.90f);
16580
0
        off = ImVec2(ImFloor(hs_w * 2.40f), ImFloor(hs_w * 2.40f));
16581
0
    }
16582
16583
0
    ImVec2 c = ImFloor(parent.GetCenter());
16584
0
    if      (dir == ImGuiDir_None)  { out_r = ImRect(c.x - hs_w, c.y - hs_w,         c.x + hs_w, c.y + hs_w);         }
16585
0
    else if (dir == ImGuiDir_Up)    { out_r = ImRect(c.x - hs_w, c.y - off.y - hs_h, c.x + hs_w, c.y - off.y + hs_h); }
16586
0
    else if (dir == ImGuiDir_Down)  { out_r = ImRect(c.x - hs_w, c.y + off.y - hs_h, c.x + hs_w, c.y + off.y + hs_h); }
16587
0
    else if (dir == ImGuiDir_Left)  { out_r = ImRect(c.x - off.x - hs_h, c.y - hs_w, c.x - off.x + hs_h, c.y + hs_w); }
16588
0
    else if (dir == ImGuiDir_Right) { out_r = ImRect(c.x + off.x - hs_h, c.y - hs_w, c.x + off.x + hs_h, c.y + hs_w); }
16589
16590
0
    if (test_mouse_pos == NULL)
16591
0
        return false;
16592
16593
0
    ImRect hit_r = out_r;
16594
0
    if (!outer_docking)
16595
0
    {
16596
        // Custom hit testing for the 5-way selection, designed to reduce flickering when moving diagonally between sides
16597
0
        hit_r.Expand(ImFloor(hs_w * 0.30f));
16598
0
        ImVec2 mouse_delta = (*test_mouse_pos - c);
16599
0
        float mouse_delta_len2 = ImLengthSqr(mouse_delta);
16600
0
        float r_threshold_center = hs_w * 1.4f;
16601
0
        float r_threshold_sides = hs_w * (1.4f + 1.2f);
16602
0
        if (mouse_delta_len2 < r_threshold_center * r_threshold_center)
16603
0
            return (dir == ImGuiDir_None);
16604
0
        if (mouse_delta_len2 < r_threshold_sides * r_threshold_sides)
16605
0
            return (dir == ImGetDirQuadrantFromDelta(mouse_delta.x, mouse_delta.y));
16606
0
    }
16607
0
    return hit_r.Contains(*test_mouse_pos);
16608
0
}
16609
16610
// host_node may be NULL if the window doesn't have a DockNode already.
16611
// FIXME-DOCK: This is misnamed since it's also doing the filtering.
16612
static void ImGui::DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* data, bool is_explicit_target, bool is_outer_docking)
16613
0
{
16614
0
    ImGuiContext& g = *GImGui;
16615
16616
    // There is an edge case when docking into a dockspace which only has inactive nodes.
16617
    // In this case DockNodeTreeFindNodeByPos() will have selected a leaf node which is inactive.
16618
    // Because the inactive leaf node doesn't have proper pos/size yet, we'll use the root node as reference.
16619
0
    if (payload_node == NULL)
16620
0
        payload_node = payload_window->DockNodeAsHost;
16621
0
    ImGuiDockNode* ref_node_for_rect = (host_node && !host_node->IsVisible) ? DockNodeGetRootNode(host_node) : host_node;
16622
0
    if (ref_node_for_rect)
16623
0
        IM_ASSERT(ref_node_for_rect->IsVisible == true);
16624
16625
    // Filter, figure out where we are allowed to dock
16626
0
    ImGuiDockNodeFlags src_node_flags = payload_node ? payload_node->MergedFlags : payload_window->WindowClass.DockNodeFlagsOverrideSet;
16627
0
    ImGuiDockNodeFlags dst_node_flags = host_node ? host_node->MergedFlags : host_window->WindowClass.DockNodeFlagsOverrideSet;
16628
0
    data->IsCenterAvailable = true;
16629
0
    if (is_outer_docking)
16630
0
        data->IsCenterAvailable = false;
16631
0
    else if (dst_node_flags & ImGuiDockNodeFlags_NoDocking)
16632
0
        data->IsCenterAvailable = false;
16633
0
    else if (host_node && (dst_node_flags & ImGuiDockNodeFlags_NoDockingInCentralNode) && host_node->IsCentralNode())
16634
0
        data->IsCenterAvailable = false;
16635
0
    else if ((!host_node || !host_node->IsEmpty()) && payload_node && payload_node->IsSplitNode() && (payload_node->OnlyNodeWithWindows == NULL)) // Is _visibly_ split?
16636
0
        data->IsCenterAvailable = false;
16637
0
    else if (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverMe)
16638
0
        data->IsCenterAvailable = false;
16639
0
    else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverOther) && (!host_node || !host_node->IsEmpty()))
16640
0
        data->IsCenterAvailable = false;
16641
0
    else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverEmpty) && host_node && host_node->IsEmpty())
16642
0
        data->IsCenterAvailable = false;
16643
16644
0
    data->IsSidesAvailable = true;
16645
0
    if ((dst_node_flags & ImGuiDockNodeFlags_NoSplit) || g.IO.ConfigDockingNoSplit)
16646
0
        data->IsSidesAvailable = false;
16647
0
    else if (!is_outer_docking && host_node && host_node->ParentNode == NULL && host_node->IsCentralNode())
16648
0
        data->IsSidesAvailable = false;
16649
0
    else if ((dst_node_flags & ImGuiDockNodeFlags_NoDockingSplitMe) || (src_node_flags & ImGuiDockNodeFlags_NoDockingSplitOther))
16650
0
        data->IsSidesAvailable = false;
16651
16652
    // Build a tentative future node (reuse same structure because it is practical. Shape will be readjusted when previewing a split)
16653
0
    data->FutureNode.HasCloseButton = (host_node ? host_node->HasCloseButton : host_window->HasCloseButton) || (payload_window->HasCloseButton);
16654
0
    data->FutureNode.HasWindowMenuButton = host_node ? true : ((host_window->Flags & ImGuiWindowFlags_NoCollapse) == 0);
16655
0
    data->FutureNode.Pos = ref_node_for_rect ? ref_node_for_rect->Pos : host_window->Pos;
16656
0
    data->FutureNode.Size = ref_node_for_rect ? ref_node_for_rect->Size : host_window->Size;
16657
16658
    // Calculate drop shapes geometry for allowed splitting directions
16659
0
    IM_ASSERT(ImGuiDir_None == -1);
16660
0
    data->SplitNode = host_node;
16661
0
    data->SplitDir = ImGuiDir_None;
16662
0
    data->IsSplitDirExplicit = false;
16663
0
    if (!host_window->Collapsed)
16664
0
        for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
16665
0
        {
16666
0
            if (dir == ImGuiDir_None && !data->IsCenterAvailable)
16667
0
                continue;
16668
0
            if (dir != ImGuiDir_None && !data->IsSidesAvailable)
16669
0
                continue;
16670
0
            if (DockNodeCalcDropRectsAndTestMousePos(data->FutureNode.Rect(), (ImGuiDir)dir, data->DropRectsDraw[dir+1], is_outer_docking, &g.IO.MousePos))
16671
0
            {
16672
0
                data->SplitDir = (ImGuiDir)dir;
16673
0
                data->IsSplitDirExplicit = true;
16674
0
            }
16675
0
        }
16676
16677
    // When docking without holding Shift, we only allow and preview docking when hovering over a drop rect or over the title bar
16678
0
    data->IsDropAllowed = (data->SplitDir != ImGuiDir_None) || (data->IsCenterAvailable);
16679
0
    if (!is_explicit_target && !data->IsSplitDirExplicit && !g.IO.ConfigDockingWithShift)
16680
0
        data->IsDropAllowed = false;
16681
16682
    // Calculate split area
16683
0
    data->SplitRatio = 0.0f;
16684
0
    if (data->SplitDir != ImGuiDir_None)
16685
0
    {
16686
0
        ImGuiDir split_dir = data->SplitDir;
16687
0
        ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
16688
0
        ImVec2 pos_new, pos_old = data->FutureNode.Pos;
16689
0
        ImVec2 size_new, size_old = data->FutureNode.Size;
16690
0
        DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, split_dir, payload_window->Size);
16691
16692
        // Calculate split ratio so we can pass it down the docking request
16693
0
        float split_ratio = ImSaturate(size_new[split_axis] / data->FutureNode.Size[split_axis]);
16694
0
        data->FutureNode.Pos = pos_new;
16695
0
        data->FutureNode.Size = size_new;
16696
0
        data->SplitRatio = (split_dir == ImGuiDir_Right || split_dir == ImGuiDir_Down) ? (1.0f - split_ratio) : (split_ratio);
16697
0
    }
16698
0
}
16699
16700
static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, const ImGuiDockPreviewData* data)
16701
0
{
16702
0
    ImGuiContext& g = *GImGui;
16703
0
    IM_ASSERT(g.CurrentWindow == host_window);   // Because we rely on font size to calculate tab sizes
16704
16705
    // With this option, we only display the preview on the target viewport, and the payload viewport is made transparent.
16706
    // To compensate for the single layer obstructed by the payload, we'll increase the alpha of the preview nodes.
16707
0
    const bool is_transparent_payload = g.IO.ConfigDockingTransparentPayload;
16708
16709
    // In case the two windows involved are on different viewports, we will draw the overlay on each of them.
16710
0
    int overlay_draw_lists_count = 0;
16711
0
    ImDrawList* overlay_draw_lists[2];
16712
0
    overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(host_window->Viewport);
16713
0
    if (host_window->Viewport != root_payload->Viewport && !is_transparent_payload)
16714
0
        overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(root_payload->Viewport);
16715
16716
    // Draw main preview rectangle
16717
0
    const ImU32 overlay_col_main = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.60f : 0.40f);
16718
0
    const ImU32 overlay_col_drop = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.90f : 0.70f);
16719
0
    const ImU32 overlay_col_drop_hovered = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 1.20f : 1.00f);
16720
0
    const ImU32 overlay_col_lines = GetColorU32(ImGuiCol_NavWindowingHighlight, is_transparent_payload ? 0.80f : 0.60f);
16721
16722
    // Display area preview
16723
0
    const bool can_preview_tabs = (root_payload->DockNodeAsHost == NULL || root_payload->DockNodeAsHost->Windows.Size > 0);
16724
0
    if (data->IsDropAllowed)
16725
0
    {
16726
0
        ImRect overlay_rect = data->FutureNode.Rect();
16727
0
        if (data->SplitDir == ImGuiDir_None && can_preview_tabs)
16728
0
            overlay_rect.Min.y += GetFrameHeight();
16729
0
        if (data->SplitDir != ImGuiDir_None || data->IsCenterAvailable)
16730
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
16731
0
                overlay_draw_lists[overlay_n]->AddRectFilled(overlay_rect.Min, overlay_rect.Max, overlay_col_main, host_window->WindowRounding, CalcRoundingFlagsForRectInRect(overlay_rect, host_window->Rect(), DOCKING_SPLITTER_SIZE));
16732
0
    }
16733
16734
    // Display tab shape/label preview unless we are splitting node (it generally makes the situation harder to read)
16735
0
    if (data->IsDropAllowed && can_preview_tabs && data->SplitDir == ImGuiDir_None && data->IsCenterAvailable)
16736
0
    {
16737
        // Compute target tab bar geometry so we can locate our preview tabs
16738
0
        ImRect tab_bar_rect;
16739
0
        DockNodeCalcTabBarLayout(&data->FutureNode, NULL, &tab_bar_rect, NULL, NULL);
16740
0
        ImVec2 tab_pos = tab_bar_rect.Min;
16741
0
        if (host_node && host_node->TabBar)
16742
0
        {
16743
0
            if (!host_node->IsHiddenTabBar() && !host_node->IsNoTabBar())
16744
0
                tab_pos.x += host_node->TabBar->WidthAllTabs + g.Style.ItemInnerSpacing.x; // We don't use OffsetNewTab because when using non-persistent-order tab bar it is incremented with each Tab submission.
16745
0
            else
16746
0
                tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_node->Windows[0]).x;
16747
0
        }
16748
0
        else if (!(host_window->Flags & ImGuiWindowFlags_DockNodeHost))
16749
0
        {
16750
0
            tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_window).x; // Account for slight offset which will be added when changing from title bar to tab bar
16751
0
        }
16752
16753
        // Draw tab shape/label preview (payload may be a loose window or a host window carrying multiple tabbed windows)
16754
0
        if (root_payload->DockNodeAsHost)
16755
0
            IM_ASSERT(root_payload->DockNodeAsHost->Windows.Size <= root_payload->DockNodeAsHost->TabBar->Tabs.Size);
16756
0
        ImGuiTabBar* tab_bar_with_payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->TabBar : NULL;
16757
0
        const int payload_count = tab_bar_with_payload ? tab_bar_with_payload->Tabs.Size : 1;
16758
0
        for (int payload_n = 0; payload_n < payload_count; payload_n++)
16759
0
        {
16760
            // DockNode's TabBar may have non-window Tabs manually appended by user
16761
0
            ImGuiWindow* payload_window = tab_bar_with_payload ? tab_bar_with_payload->Tabs[payload_n].Window : root_payload;
16762
0
            if (tab_bar_with_payload && payload_window == NULL)
16763
0
                continue;
16764
0
            if (!DockNodeIsDropAllowedOne(payload_window, host_window))
16765
0
                continue;
16766
16767
            // Calculate the tab bounding box for each payload window
16768
0
            ImVec2 tab_size = TabItemCalcSize(payload_window);
16769
0
            ImRect tab_bb(tab_pos.x, tab_pos.y, tab_pos.x + tab_size.x, tab_pos.y + tab_size.y);
16770
0
            tab_pos.x += tab_size.x + g.Style.ItemInnerSpacing.x;
16771
0
            const ImU32 overlay_col_text = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_Text]);
16772
0
            const ImU32 overlay_col_tabs = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_TabActive]);
16773
0
            PushStyleColor(ImGuiCol_Text, overlay_col_text);
16774
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
16775
0
            {
16776
0
                ImGuiTabItemFlags tab_flags = ImGuiTabItemFlags_Preview | ((payload_window->Flags & ImGuiWindowFlags_UnsavedDocument) ? ImGuiTabItemFlags_UnsavedDocument : 0);
16777
0
                if (!tab_bar_rect.Contains(tab_bb))
16778
0
                    overlay_draw_lists[overlay_n]->PushClipRect(tab_bar_rect.Min, tab_bar_rect.Max);
16779
0
                TabItemBackground(overlay_draw_lists[overlay_n], tab_bb, tab_flags, overlay_col_tabs);
16780
0
                TabItemLabelAndCloseButton(overlay_draw_lists[overlay_n], tab_bb, tab_flags, g.Style.FramePadding, payload_window->Name, 0, 0, false, NULL, NULL);
16781
0
                if (!tab_bar_rect.Contains(tab_bb))
16782
0
                    overlay_draw_lists[overlay_n]->PopClipRect();
16783
0
            }
16784
0
            PopStyleColor();
16785
0
        }
16786
0
    }
16787
16788
    // Display drop boxes
16789
0
    const float overlay_rounding = ImMax(3.0f, g.Style.FrameRounding);
16790
0
    for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
16791
0
    {
16792
0
        if (!data->DropRectsDraw[dir + 1].IsInverted())
16793
0
        {
16794
0
            ImRect draw_r = data->DropRectsDraw[dir + 1];
16795
0
            ImRect draw_r_in = draw_r;
16796
0
            draw_r_in.Expand(-2.0f);
16797
0
            ImU32 overlay_col = (data->SplitDir == (ImGuiDir)dir && data->IsSplitDirExplicit) ? overlay_col_drop_hovered : overlay_col_drop;
16798
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
16799
0
            {
16800
0
                ImVec2 center = ImFloor(draw_r_in.GetCenter());
16801
0
                overlay_draw_lists[overlay_n]->AddRectFilled(draw_r.Min, draw_r.Max, overlay_col, overlay_rounding);
16802
0
                overlay_draw_lists[overlay_n]->AddRect(draw_r_in.Min, draw_r_in.Max, overlay_col_lines, overlay_rounding);
16803
0
                if (dir == ImGuiDir_Left || dir == ImGuiDir_Right)
16804
0
                    overlay_draw_lists[overlay_n]->AddLine(ImVec2(center.x, draw_r_in.Min.y), ImVec2(center.x, draw_r_in.Max.y), overlay_col_lines);
16805
0
                if (dir == ImGuiDir_Up || dir == ImGuiDir_Down)
16806
0
                    overlay_draw_lists[overlay_n]->AddLine(ImVec2(draw_r_in.Min.x, center.y), ImVec2(draw_r_in.Max.x, center.y), overlay_col_lines);
16807
0
            }
16808
0
        }
16809
16810
        // Stop after ImGuiDir_None
16811
0
        if ((host_node && (host_node->MergedFlags & ImGuiDockNodeFlags_NoSplit)) || g.IO.ConfigDockingNoSplit)
16812
0
            return;
16813
0
    }
16814
0
}
16815
16816
//-----------------------------------------------------------------------------
16817
// Docking: ImGuiDockNode Tree manipulation functions
16818
//-----------------------------------------------------------------------------
16819
// - DockNodeTreeSplit()
16820
// - DockNodeTreeMerge()
16821
// - DockNodeTreeUpdatePosSize()
16822
// - DockNodeTreeUpdateSplitterFindTouchingNode()
16823
// - DockNodeTreeUpdateSplitter()
16824
// - DockNodeTreeFindFallbackLeafNode()
16825
// - DockNodeTreeFindNodeByPos()
16826
//-----------------------------------------------------------------------------
16827
16828
void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_inheritor_child_idx, float split_ratio, ImGuiDockNode* new_node)
16829
0
{
16830
0
    ImGuiContext& g = *GImGui;
16831
0
    IM_ASSERT(split_axis != ImGuiAxis_None);
16832
16833
0
    ImGuiDockNode* child_0 = (new_node && split_inheritor_child_idx != 0) ? new_node : DockContextAddNode(ctx, 0);
16834
0
    child_0->ParentNode = parent_node;
16835
16836
0
    ImGuiDockNode* child_1 = (new_node && split_inheritor_child_idx != 1) ? new_node : DockContextAddNode(ctx, 0);
16837
0
    child_1->ParentNode = parent_node;
16838
16839
0
    ImGuiDockNode* child_inheritor = (split_inheritor_child_idx == 0) ? child_0 : child_1;
16840
0
    DockNodeMoveChildNodes(child_inheritor, parent_node);
16841
0
    parent_node->ChildNodes[0] = child_0;
16842
0
    parent_node->ChildNodes[1] = child_1;
16843
0
    parent_node->ChildNodes[split_inheritor_child_idx]->VisibleWindow = parent_node->VisibleWindow;
16844
0
    parent_node->SplitAxis = split_axis;
16845
0
    parent_node->VisibleWindow = NULL;
16846
0
    parent_node->AuthorityForPos = parent_node->AuthorityForSize = ImGuiDataAuthority_DockNode;
16847
16848
0
    float size_avail = (parent_node->Size[split_axis] - DOCKING_SPLITTER_SIZE);
16849
0
    size_avail = ImMax(size_avail, g.Style.WindowMinSize[split_axis] * 2.0f);
16850
0
    IM_ASSERT(size_avail > 0.0f); // If you created a node manually with DockBuilderAddNode(), you need to also call DockBuilderSetNodeSize() before splitting.
16851
0
    child_0->SizeRef = child_1->SizeRef = parent_node->Size;
16852
0
    child_0->SizeRef[split_axis] = ImFloor(size_avail * split_ratio);
16853
0
    child_1->SizeRef[split_axis] = ImFloor(size_avail - child_0->SizeRef[split_axis]);
16854
16855
0
    DockNodeMoveWindows(parent_node->ChildNodes[split_inheritor_child_idx], parent_node);
16856
0
    DockSettingsRenameNodeReferences(parent_node->ID, parent_node->ChildNodes[split_inheritor_child_idx]->ID);
16857
0
    DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(parent_node));
16858
0
    DockNodeTreeUpdatePosSize(parent_node, parent_node->Pos, parent_node->Size);
16859
16860
    // Flags transfer (e.g. this is where we transfer the ImGuiDockNodeFlags_CentralNode property)
16861
0
    child_0->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
16862
0
    child_1->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
16863
0
    child_inheritor->LocalFlags = parent_node->LocalFlags & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
16864
0
    parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_;
16865
0
    child_0->UpdateMergedFlags();
16866
0
    child_1->UpdateMergedFlags();
16867
0
    parent_node->UpdateMergedFlags();
16868
0
    if (child_inheritor->IsCentralNode())
16869
0
        DockNodeGetRootNode(parent_node)->CentralNode = child_inheritor;
16870
0
}
16871
16872
void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child)
16873
0
{
16874
    // When called from DockContextProcessUndockNode() it is possible that one of the child is NULL.
16875
0
    ImGuiContext& g = *GImGui;
16876
0
    ImGuiDockNode* child_0 = parent_node->ChildNodes[0];
16877
0
    ImGuiDockNode* child_1 = parent_node->ChildNodes[1];
16878
0
    IM_ASSERT(child_0 || child_1);
16879
0
    IM_ASSERT(merge_lead_child == child_0 || merge_lead_child == child_1);
16880
0
    if ((child_0 && child_0->Windows.Size > 0) || (child_1 && child_1->Windows.Size > 0))
16881
0
    {
16882
0
        IM_ASSERT(parent_node->TabBar == NULL);
16883
0
        IM_ASSERT(parent_node->Windows.Size == 0);
16884
0
    }
16885
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeTreeMerge: 0x%08X + 0x%08X back into parent 0x%08X\n", child_0 ? child_0->ID : 0, child_1 ? child_1->ID : 0, parent_node->ID);
16886
16887
0
    ImVec2 backup_last_explicit_size = parent_node->SizeRef;
16888
0
    DockNodeMoveChildNodes(parent_node, merge_lead_child);
16889
0
    if (child_0)
16890
0
    {
16891
0
        DockNodeMoveWindows(parent_node, child_0); // Generally only 1 of the 2 child node will have windows
16892
0
        DockSettingsRenameNodeReferences(child_0->ID, parent_node->ID);
16893
0
    }
16894
0
    if (child_1)
16895
0
    {
16896
0
        DockNodeMoveWindows(parent_node, child_1);
16897
0
        DockSettingsRenameNodeReferences(child_1->ID, parent_node->ID);
16898
0
    }
16899
0
    DockNodeApplyPosSizeToWindows(parent_node);
16900
0
    parent_node->AuthorityForPos = parent_node->AuthorityForSize = parent_node->AuthorityForViewport = ImGuiDataAuthority_Auto;
16901
0
    parent_node->VisibleWindow = merge_lead_child->VisibleWindow;
16902
0
    parent_node->SizeRef = backup_last_explicit_size;
16903
16904
    // Flags transfer
16905
0
    parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; // Preserve Dockspace flag
16906
0
    parent_node->LocalFlags |= (child_0 ? child_0->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
16907
0
    parent_node->LocalFlags |= (child_1 ? child_1->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
16908
0
    parent_node->LocalFlagsInWindows = (child_0 ? child_0->LocalFlagsInWindows : 0) | (child_1 ? child_1->LocalFlagsInWindows : 0); // FIXME: Would be more consistent to update from actual windows
16909
0
    parent_node->UpdateMergedFlags();
16910
16911
0
    if (child_0)
16912
0
    {
16913
0
        ctx->DockContext.Nodes.SetVoidPtr(child_0->ID, NULL);
16914
0
        IM_DELETE(child_0);
16915
0
    }
16916
0
    if (child_1)
16917
0
    {
16918
0
        ctx->DockContext.Nodes.SetVoidPtr(child_1->ID, NULL);
16919
0
        IM_DELETE(child_1);
16920
0
    }
16921
0
}
16922
16923
// Update Pos/Size for a node hierarchy (don't affect child Windows yet)
16924
// (Depth-first, Pre-Order)
16925
void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node)
16926
0
{
16927
    // During the regular dock node update we write to all nodes.
16928
    // 'only_write_to_single_node' is only set when turning a node visible mid-frame and we need its size right-away.
16929
0
    const bool write_to_node = only_write_to_single_node == NULL || only_write_to_single_node == node;
16930
0
    if (write_to_node)
16931
0
    {
16932
0
        node->Pos = pos;
16933
0
        node->Size = size;
16934
0
    }
16935
16936
0
    if (node->IsLeafNode())
16937
0
        return;
16938
16939
0
    ImGuiDockNode* child_0 = node->ChildNodes[0];
16940
0
    ImGuiDockNode* child_1 = node->ChildNodes[1];
16941
0
    ImVec2 child_0_pos = pos, child_1_pos = pos;
16942
0
    ImVec2 child_0_size = size, child_1_size = size;
16943
16944
0
    const bool child_0_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_0));
16945
0
    const bool child_1_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_1));
16946
0
    const bool child_0_is_or_will_be_visible = child_0->IsVisible || child_0_is_toward_single_node;
16947
0
    const bool child_1_is_or_will_be_visible = child_1->IsVisible || child_1_is_toward_single_node;
16948
16949
0
    if (child_0_is_or_will_be_visible && child_1_is_or_will_be_visible)
16950
0
    {
16951
0
        ImGuiContext& g = *GImGui;
16952
0
        const float spacing = DOCKING_SPLITTER_SIZE;
16953
0
        const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
16954
0
        const float size_avail = ImMax(size[axis] - spacing, 0.0f);
16955
16956
        // Size allocation policy
16957
        // 1) The first 0..WindowMinSize[axis]*2 are allocated evenly to both windows.
16958
0
        const float size_min_each = ImFloor(ImMin(size_avail, g.Style.WindowMinSize[axis] * 2.0f) * 0.5f);
16959
16960
        // FIXME: Blocks 2) and 3) are essentially doing nearly the same thing.
16961
        // Difference are: write-back to SizeRef; application of a minimum size; rounding before ImFloor()
16962
        // Clarify and rework differences between Size & SizeRef and purpose of WantLockSizeOnce
16963
16964
        // 2) Process locked absolute size (during a splitter resize we preserve the child of nodes not touching the splitter edge)
16965
0
        if (child_0->WantLockSizeOnce && !child_1->WantLockSizeOnce)
16966
0
        {
16967
0
            child_0_size[axis] = child_0->SizeRef[axis] = ImMin(size_avail - 1.0f, child_0->Size[axis]);
16968
0
            child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
16969
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
16970
0
        }
16971
0
        else if (child_1->WantLockSizeOnce && !child_0->WantLockSizeOnce)
16972
0
        {
16973
0
            child_1_size[axis] = child_1->SizeRef[axis] = ImMin(size_avail - 1.0f, child_1->Size[axis]);
16974
0
            child_0_size[axis] = child_0->SizeRef[axis] = (size_avail - child_1_size[axis]);
16975
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
16976
0
        }
16977
0
        else if (child_0->WantLockSizeOnce && child_1->WantLockSizeOnce)
16978
0
        {
16979
            // FIXME-DOCK: We cannot honor the requested size, so apply ratio.
16980
            // Currently this path will only be taken if code programmatically sets WantLockSizeOnce
16981
0
            float split_ratio = child_0_size[axis] / (child_0_size[axis] + child_1_size[axis]);
16982
0
            child_0_size[axis] = child_0->SizeRef[axis] = ImFloor(size_avail * split_ratio);
16983
0
            child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
16984
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
16985
0
        }
16986
16987
        // 3) If one window is the central node (~ use remaining space, should be made explicit!), use explicit size from the other, and remainder for the central node
16988
0
        else if (child_0->SizeRef[axis] != 0.0f && child_1->HasCentralNodeChild)
16989
0
        {
16990
0
            child_0_size[axis] = ImMin(size_avail - size_min_each, child_0->SizeRef[axis]);
16991
0
            child_1_size[axis] = (size_avail - child_0_size[axis]);
16992
0
        }
16993
0
        else if (child_1->SizeRef[axis] != 0.0f && child_0->HasCentralNodeChild)
16994
0
        {
16995
0
            child_1_size[axis] = ImMin(size_avail - size_min_each, child_1->SizeRef[axis]);
16996
0
            child_0_size[axis] = (size_avail - child_1_size[axis]);
16997
0
        }
16998
0
        else
16999
0
        {
17000
            // 4) Otherwise distribute according to the relative ratio of each SizeRef value
17001
0
            float split_ratio = child_0->SizeRef[axis] / (child_0->SizeRef[axis] + child_1->SizeRef[axis]);
17002
0
            child_0_size[axis] = ImMax(size_min_each, ImFloor(size_avail * split_ratio + 0.5f));
17003
0
            child_1_size[axis] = (size_avail - child_0_size[axis]);
17004
0
        }
17005
17006
0
        child_1_pos[axis] += spacing + child_0_size[axis];
17007
0
    }
17008
17009
0
    if (only_write_to_single_node == NULL)
17010
0
        child_0->WantLockSizeOnce = child_1->WantLockSizeOnce = false;
17011
17012
0
    const bool child_0_recurse = only_write_to_single_node ? child_0_is_toward_single_node : child_0->IsVisible;
17013
0
    const bool child_1_recurse = only_write_to_single_node ? child_1_is_toward_single_node : child_1->IsVisible;
17014
0
    if (child_0_recurse)
17015
0
        DockNodeTreeUpdatePosSize(child_0, child_0_pos, child_0_size);
17016
0
    if (child_1_recurse)
17017
0
        DockNodeTreeUpdatePosSize(child_1, child_1_pos, child_1_size);
17018
0
}
17019
17020
static void DockNodeTreeUpdateSplitterFindTouchingNode(ImGuiDockNode* node, ImGuiAxis axis, int side, ImVector<ImGuiDockNode*>* touching_nodes)
17021
0
{
17022
0
    if (node->IsLeafNode())
17023
0
    {
17024
0
        touching_nodes->push_back(node);
17025
0
        return;
17026
0
    }
17027
0
    if (node->ChildNodes[0]->IsVisible)
17028
0
        if (node->SplitAxis != axis || side == 0 || !node->ChildNodes[1]->IsVisible)
17029
0
            DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[0], axis, side, touching_nodes);
17030
0
    if (node->ChildNodes[1]->IsVisible)
17031
0
        if (node->SplitAxis != axis || side == 1 || !node->ChildNodes[0]->IsVisible)
17032
0
            DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[1], axis, side, touching_nodes);
17033
0
}
17034
17035
// (Depth-First, Pre-Order)
17036
void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node)
17037
0
{
17038
0
    if (node->IsLeafNode())
17039
0
        return;
17040
17041
0
    ImGuiContext& g = *GImGui;
17042
17043
0
    ImGuiDockNode* child_0 = node->ChildNodes[0];
17044
0
    ImGuiDockNode* child_1 = node->ChildNodes[1];
17045
0
    if (child_0->IsVisible && child_1->IsVisible)
17046
0
    {
17047
        // Bounding box of the splitter cover the space between both nodes (w = Spacing, h = Size[xy^1] for when splitting horizontally)
17048
0
        const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
17049
0
        IM_ASSERT(axis != ImGuiAxis_None);
17050
0
        ImRect bb;
17051
0
        bb.Min = child_0->Pos;
17052
0
        bb.Max = child_1->Pos;
17053
0
        bb.Min[axis] += child_0->Size[axis];
17054
0
        bb.Max[axis ^ 1] += child_1->Size[axis ^ 1];
17055
        //if (g.IO.KeyCtrl) GetForegroundDrawList(g.CurrentWindow->Viewport)->AddRect(bb.Min, bb.Max, IM_COL32(255,0,255,255));
17056
17057
0
        const ImGuiDockNodeFlags merged_flags = child_0->MergedFlags | child_1->MergedFlags; // Merged flags for BOTH childs
17058
0
        const ImGuiDockNodeFlags no_resize_axis_flag = (axis == ImGuiAxis_X) ? ImGuiDockNodeFlags_NoResizeX : ImGuiDockNodeFlags_NoResizeY;
17059
0
        if ((merged_flags & ImGuiDockNodeFlags_NoResize) || (merged_flags & no_resize_axis_flag))
17060
0
        {
17061
0
            ImGuiWindow* window = g.CurrentWindow;
17062
0
            window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator), g.Style.FrameRounding);
17063
0
        }
17064
0
        else
17065
0
        {
17066
            //bb.Min[axis] += 1; // Display a little inward so highlight doesn't connect with nearby tabs on the neighbor node.
17067
            //bb.Max[axis] -= 1;
17068
0
            PushID(node->ID);
17069
17070
            // Find resizing limits by gathering list of nodes that are touching the splitter line.
17071
0
            ImVector<ImGuiDockNode*> touching_nodes[2];
17072
0
            float min_size = g.Style.WindowMinSize[axis];
17073
0
            float resize_limits[2];
17074
0
            resize_limits[0] = node->ChildNodes[0]->Pos[axis] + min_size;
17075
0
            resize_limits[1] = node->ChildNodes[1]->Pos[axis] + node->ChildNodes[1]->Size[axis] - min_size;
17076
17077
0
            ImGuiID splitter_id = GetID("##Splitter");
17078
0
            if (g.ActiveId == splitter_id) // Only process when splitter is active
17079
0
            {
17080
0
                DockNodeTreeUpdateSplitterFindTouchingNode(child_0, axis, 1, &touching_nodes[0]);
17081
0
                DockNodeTreeUpdateSplitterFindTouchingNode(child_1, axis, 0, &touching_nodes[1]);
17082
0
                for (int touching_node_n = 0; touching_node_n < touching_nodes[0].Size; touching_node_n++)
17083
0
                    resize_limits[0] = ImMax(resize_limits[0], touching_nodes[0][touching_node_n]->Rect().Min[axis] + min_size);
17084
0
                for (int touching_node_n = 0; touching_node_n < touching_nodes[1].Size; touching_node_n++)
17085
0
                    resize_limits[1] = ImMin(resize_limits[1], touching_nodes[1][touching_node_n]->Rect().Max[axis] - min_size);
17086
17087
                // [DEBUG] Render touching nodes & limits
17088
                /*
17089
                ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
17090
                for (int n = 0; n < 2; n++)
17091
                {
17092
                    for (int touching_node_n = 0; touching_node_n < touching_nodes[n].Size; touching_node_n++)
17093
                        draw_list->AddRect(touching_nodes[n][touching_node_n]->Pos, touching_nodes[n][touching_node_n]->Pos + touching_nodes[n][touching_node_n]->Size, IM_COL32(0, 255, 0, 255));
17094
                    if (axis == ImGuiAxis_X)
17095
                        draw_list->AddLine(ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y), ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y + node->ChildNodes[n]->Size.y), IM_COL32(255, 0, 255, 255), 3.0f);
17096
                    else
17097
                        draw_list->AddLine(ImVec2(node->ChildNodes[n]->Pos.x, resize_limits[n]), ImVec2(node->ChildNodes[n]->Pos.x + node->ChildNodes[n]->Size.x, resize_limits[n]), IM_COL32(255, 0, 255, 255), 3.0f);
17098
                }
17099
                */
17100
0
            }
17101
17102
            // Use a short delay before highlighting the splitter (and changing the mouse cursor) in order for regular mouse movement to not highlight many splitters
17103
0
            float cur_size_0 = child_0->Size[axis];
17104
0
            float cur_size_1 = child_1->Size[axis];
17105
0
            float min_size_0 = resize_limits[0] - child_0->Pos[axis];
17106
0
            float min_size_1 = child_1->Pos[axis] + child_1->Size[axis] - resize_limits[1];
17107
0
            ImU32 bg_col = GetColorU32(ImGuiCol_WindowBg);
17108
0
            if (SplitterBehavior(bb, GetID("##Splitter"), axis, &cur_size_0, &cur_size_1, min_size_0, min_size_1, WINDOWS_HOVER_PADDING, WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER, bg_col))
17109
0
            {
17110
0
                if (touching_nodes[0].Size > 0 && touching_nodes[1].Size > 0)
17111
0
                {
17112
0
                    child_0->Size[axis] = child_0->SizeRef[axis] = cur_size_0;
17113
0
                    child_1->Pos[axis] -= cur_size_1 - child_1->Size[axis];
17114
0
                    child_1->Size[axis] = child_1->SizeRef[axis] = cur_size_1;
17115
17116
                    // Lock the size of every node that is a sibling of the node we are touching
17117
                    // This might be less desirable if we can merge sibling of a same axis into the same parental level.
17118
0
                    for (int side_n = 0; side_n < 2; side_n++)
17119
0
                        for (int touching_node_n = 0; touching_node_n < touching_nodes[side_n].Size; touching_node_n++)
17120
0
                        {
17121
0
                            ImGuiDockNode* touching_node = touching_nodes[side_n][touching_node_n];
17122
                            //ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
17123
                            //draw_list->AddRect(touching_node->Pos, touching_node->Pos + touching_node->Size, IM_COL32(255, 128, 0, 255));
17124
0
                            while (touching_node->ParentNode != node)
17125
0
                            {
17126
0
                                if (touching_node->ParentNode->SplitAxis == axis)
17127
0
                                {
17128
                                    // Mark other node so its size will be preserved during the upcoming call to DockNodeTreeUpdatePosSize().
17129
0
                                    ImGuiDockNode* node_to_preserve = touching_node->ParentNode->ChildNodes[side_n];
17130
0
                                    node_to_preserve->WantLockSizeOnce = true;
17131
                                    //draw_list->AddRect(touching_node->Pos, touching_node->Rect().Max, IM_COL32(255, 0, 0, 255));
17132
                                    //draw_list->AddRectFilled(node_to_preserve->Pos, node_to_preserve->Rect().Max, IM_COL32(0, 255, 0, 100));
17133
0
                                }
17134
0
                                touching_node = touching_node->ParentNode;
17135
0
                            }
17136
0
                        }
17137
17138
0
                    DockNodeTreeUpdatePosSize(child_0, child_0->Pos, child_0->Size);
17139
0
                    DockNodeTreeUpdatePosSize(child_1, child_1->Pos, child_1->Size);
17140
0
                    MarkIniSettingsDirty();
17141
0
                }
17142
0
            }
17143
0
            PopID();
17144
0
        }
17145
0
    }
17146
17147
0
    if (child_0->IsVisible)
17148
0
        DockNodeTreeUpdateSplitter(child_0);
17149
0
    if (child_1->IsVisible)
17150
0
        DockNodeTreeUpdateSplitter(child_1);
17151
0
}
17152
17153
ImGuiDockNode* ImGui::DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node)
17154
0
{
17155
0
    if (node->IsLeafNode())
17156
0
        return node;
17157
0
    if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[0]))
17158
0
        return leaf_node;
17159
0
    if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[1]))
17160
0
        return leaf_node;
17161
0
    return NULL;
17162
0
}
17163
17164
ImGuiDockNode* ImGui::DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos)
17165
0
{
17166
0
    if (!node->IsVisible)
17167
0
        return NULL;
17168
17169
0
    const float dock_spacing = 0.0f;// g.Style.ItemInnerSpacing.x; // FIXME: Relation to DOCKING_SPLITTER_SIZE?
17170
0
    ImRect r(node->Pos, node->Pos + node->Size);
17171
0
    r.Expand(dock_spacing * 0.5f);
17172
0
    bool inside = r.Contains(pos);
17173
0
    if (!inside)
17174
0
        return NULL;
17175
17176
0
    if (node->IsLeafNode())
17177
0
        return node;
17178
0
    if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[0], pos))
17179
0
        return hovered_node;
17180
0
    if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[1], pos))
17181
0
        return hovered_node;
17182
17183
    // This means we are hovering over the splitter/spacing of a parent node
17184
0
    return node;
17185
0
}
17186
17187
//-----------------------------------------------------------------------------
17188
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
17189
//-----------------------------------------------------------------------------
17190
// - SetWindowDock() [Internal]
17191
// - DockSpace()
17192
// - DockSpaceOverViewport()
17193
//-----------------------------------------------------------------------------
17194
17195
// [Internal] Called via SetNextWindowDockID()
17196
void ImGui::SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond)
17197
0
{
17198
    // Test condition (NB: bit 0 is always true) and clear flags for next time
17199
0
    if (cond && (window->SetWindowDockAllowFlags & cond) == 0)
17200
0
        return;
17201
0
    window->SetWindowDockAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
17202
17203
0
    if (window->DockId == dock_id)
17204
0
        return;
17205
17206
    // If the user attempt to set a dock id that is a split node, we'll dig within to find a suitable docking spot
17207
0
    ImGuiContext* ctx = GImGui;
17208
0
    if (ImGuiDockNode* new_node = DockContextFindNodeByID(ctx, dock_id))
17209
0
        if (new_node->IsSplitNode())
17210
0
        {
17211
            // Policy: Find central node or latest focused node. We first move back to our root node.
17212
0
            new_node = DockNodeGetRootNode(new_node);
17213
0
            if (new_node->CentralNode)
17214
0
            {
17215
0
                IM_ASSERT(new_node->CentralNode->IsCentralNode());
17216
0
                dock_id = new_node->CentralNode->ID;
17217
0
            }
17218
0
            else
17219
0
            {
17220
0
                dock_id = new_node->LastFocusedNodeId;
17221
0
            }
17222
0
        }
17223
17224
0
    if (window->DockId == dock_id)
17225
0
        return;
17226
17227
0
    if (window->DockNode)
17228
0
        DockNodeRemoveWindow(window->DockNode, window, 0);
17229
0
    window->DockId = dock_id;
17230
0
}
17231
17232
// Create an explicit dockspace node within an existing window. Also expose dock node flags and creates a CentralNode by default.
17233
// The Central Node is always displayed even when empty and shrink/extend according to the requested size of its neighbors.
17234
// DockSpace() needs to be submitted _before_ any window they can host. If you use a dockspace, submit it early in your app.
17235
// When ImGuiDockNodeFlags_KeepAliveOnly is set, nothing is submitted in the current window (function may be called from any location).
17236
ImGuiID ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags flags, const ImGuiWindowClass* window_class)
17237
0
{
17238
0
    ImGuiContext* ctx = GImGui;
17239
0
    ImGuiContext& g = *ctx;
17240
0
    ImGuiWindow* window = GetCurrentWindowRead();
17241
0
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
17242
0
        return 0;
17243
17244
    // Early out if parent window is hidden/collapsed
17245
    // This is faster but also DockNodeUpdateTabBar() relies on TabBarLayout() running (which won't if SkipItems=true) to set NextSelectedTabId = 0). See #2960.
17246
    // If for whichever reason this is causing problem we would need to ensure that DockNodeUpdateTabBar() ends up clearing NextSelectedTabId even if SkipItems=true.
17247
0
    if (window->SkipItems)
17248
0
        flags |= ImGuiDockNodeFlags_KeepAliveOnly;
17249
0
    if ((flags & ImGuiDockNodeFlags_KeepAliveOnly) == 0)
17250
0
        window = GetCurrentWindow(); // call to set window->WriteAccessed = true;
17251
17252
0
    IM_ASSERT((flags & ImGuiDockNodeFlags_DockSpace) == 0);
17253
0
    IM_ASSERT(id != 0);
17254
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, id);
17255
0
    if (!node)
17256
0
    {
17257
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X created\n", id);
17258
0
        node = DockContextAddNode(ctx, id);
17259
0
        node->SetLocalFlags(ImGuiDockNodeFlags_CentralNode);
17260
0
    }
17261
0
    if (window_class && window_class->ClassId != node->WindowClass.ClassId)
17262
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X: setup WindowClass 0x%08X -> 0x%08X\n", id, node->WindowClass.ClassId, window_class->ClassId);
17263
0
    node->SharedFlags = flags;
17264
0
    node->WindowClass = window_class ? *window_class : ImGuiWindowClass();
17265
17266
    // When a DockSpace transitioned form implicit to explicit this may be called a second time
17267
    // It is possible that the node has already been claimed by a docked window which appeared before the DockSpace() node, so we overwrite IsDockSpace again.
17268
0
    if (node->LastFrameActive == g.FrameCount && !(flags & ImGuiDockNodeFlags_KeepAliveOnly))
17269
0
    {
17270
0
        IM_ASSERT(node->IsDockSpace() == false && "Cannot call DockSpace() twice a frame with the same ID");
17271
0
        node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
17272
0
        return id;
17273
0
    }
17274
0
    node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
17275
17276
    // Keep alive mode, this is allow windows docked into this node so stay docked even if they are not visible
17277
0
    if (flags & ImGuiDockNodeFlags_KeepAliveOnly)
17278
0
    {
17279
0
        node->LastFrameAlive = g.FrameCount;
17280
0
        return id;
17281
0
    }
17282
17283
0
    const ImVec2 content_avail = GetContentRegionAvail();
17284
0
    ImVec2 size = ImFloor(size_arg);
17285
0
    if (size.x <= 0.0f)
17286
0
        size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
17287
0
    if (size.y <= 0.0f)
17288
0
        size.y = ImMax(content_avail.y + size.y, 4.0f);
17289
0
    IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
17290
17291
0
    node->Pos = window->DC.CursorPos;
17292
0
    node->Size = node->SizeRef = size;
17293
0
    SetNextWindowPos(node->Pos);
17294
0
    SetNextWindowSize(node->Size);
17295
0
    g.NextWindowData.PosUndock = false;
17296
17297
    // FIXME-DOCK: Why do we need a child window to host a dockspace, could we host it in the existing window?
17298
    // FIXME-DOCK: What is the reason for not simply calling BeginChild()? (OK to have a reason but should be commented)
17299
0
    ImGuiWindowFlags window_flags = ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_DockNodeHost;
17300
0
    window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar;
17301
0
    window_flags |= ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse;
17302
0
    window_flags |= ImGuiWindowFlags_NoBackground;
17303
17304
0
    char title[256];
17305
0
    ImFormatString(title, IM_ARRAYSIZE(title), "%s/DockSpace_%08X", window->Name, id);
17306
17307
0
    PushStyleVar(ImGuiStyleVar_ChildBorderSize, 0.0f);
17308
0
    Begin(title, NULL, window_flags);
17309
0
    PopStyleVar();
17310
17311
0
    ImGuiWindow* host_window = g.CurrentWindow;
17312
0
    DockNodeSetupHostWindow(node, host_window);
17313
0
    host_window->ChildId = window->GetID(title);
17314
0
    node->OnlyNodeWithWindows = NULL;
17315
17316
0
    IM_ASSERT(node->IsRootNode());
17317
17318
    // We need to handle the rare case were a central node is missing.
17319
    // This can happen if the node was first created manually with DockBuilderAddNode() but _without_ the ImGuiDockNodeFlags_Dockspace.
17320
    // Doing it correctly would set the _CentralNode flags, which would then propagate according to subsequent split.
17321
    // It would also be ambiguous to attempt to assign a central node while there are split nodes, so we wait until there's a single node remaining.
17322
    // The specific sub-property of _CentralNode we are interested in recovering here is the "Don't delete when empty" property,
17323
    // as it doesn't make sense for an empty dockspace to not have this property.
17324
0
    if (node->IsLeafNode() && !node->IsCentralNode())
17325
0
        node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
17326
17327
    // Update the node
17328
0
    DockNodeUpdate(node);
17329
17330
0
    End();
17331
0
    ItemSize(size);
17332
0
    return id;
17333
0
}
17334
17335
// Tips: Use with ImGuiDockNodeFlags_PassthruCentralNode!
17336
// The limitation with this call is that your window won't have a menu bar.
17337
// Even though we could pass window flags, it would also require the user to be able to call BeginMenuBar() somehow meaning we can't Begin/End in a single function.
17338
// But you can also use BeginMainMenuBar(). If you really want a menu bar inside the same window as the one hosting the dockspace, you will need to copy this code somewhere and tweak it.
17339
ImGuiID ImGui::DockSpaceOverViewport(const ImGuiViewport* viewport, ImGuiDockNodeFlags dockspace_flags, const ImGuiWindowClass* window_class)
17340
0
{
17341
0
    if (viewport == NULL)
17342
0
        viewport = GetMainViewport();
17343
17344
0
    SetNextWindowPos(viewport->WorkPos);
17345
0
    SetNextWindowSize(viewport->WorkSize);
17346
0
    SetNextWindowViewport(viewport->ID);
17347
17348
0
    ImGuiWindowFlags host_window_flags = 0;
17349
0
    host_window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking;
17350
0
    host_window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
17351
0
    if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode)
17352
0
        host_window_flags |= ImGuiWindowFlags_NoBackground;
17353
17354
0
    char label[32];
17355
0
    ImFormatString(label, IM_ARRAYSIZE(label), "DockSpaceViewport_%08X", viewport->ID);
17356
17357
0
    PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
17358
0
    PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
17359
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
17360
0
    Begin(label, NULL, host_window_flags);
17361
0
    PopStyleVar(3);
17362
17363
0
    ImGuiID dockspace_id = GetID("DockSpace");
17364
0
    DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags, window_class);
17365
0
    End();
17366
17367
0
    return dockspace_id;
17368
0
}
17369
17370
//-----------------------------------------------------------------------------
17371
// Docking: Builder Functions
17372
//-----------------------------------------------------------------------------
17373
// Very early end-user API to manipulate dock nodes.
17374
// Only available in imgui_internal.h. Expect this API to change/break!
17375
// It is expected that those functions are all called _before_ the dockspace node submission.
17376
//-----------------------------------------------------------------------------
17377
// - DockBuilderDockWindow()
17378
// - DockBuilderGetNode()
17379
// - DockBuilderSetNodePos()
17380
// - DockBuilderSetNodeSize()
17381
// - DockBuilderAddNode()
17382
// - DockBuilderRemoveNode()
17383
// - DockBuilderRemoveNodeChildNodes()
17384
// - DockBuilderRemoveNodeDockedWindows()
17385
// - DockBuilderSplitNode()
17386
// - DockBuilderCopyNodeRec()
17387
// - DockBuilderCopyNode()
17388
// - DockBuilderCopyWindowSettings()
17389
// - DockBuilderCopyDockSpace()
17390
// - DockBuilderFinish()
17391
//-----------------------------------------------------------------------------
17392
17393
void ImGui::DockBuilderDockWindow(const char* window_name, ImGuiID node_id)
17394
0
{
17395
    // We don't preserve relative order of multiple docked windows (by clearing DockOrder back to -1)
17396
0
    ImGuiID window_id = ImHashStr(window_name);
17397
0
    if (ImGuiWindow* window = FindWindowByID(window_id))
17398
0
    {
17399
        // Apply to created window
17400
0
        SetWindowDock(window, node_id, ImGuiCond_Always);
17401
0
        window->DockOrder = -1;
17402
0
    }
17403
0
    else
17404
0
    {
17405
        // Apply to settings
17406
0
        ImGuiWindowSettings* settings = FindWindowSettings(window_id);
17407
0
        if (settings == NULL)
17408
0
            settings = CreateNewWindowSettings(window_name);
17409
0
        settings->DockId = node_id;
17410
0
        settings->DockOrder = -1;
17411
0
    }
17412
0
}
17413
17414
ImGuiDockNode* ImGui::DockBuilderGetNode(ImGuiID node_id)
17415
0
{
17416
0
    ImGuiContext* ctx = GImGui;
17417
0
    return DockContextFindNodeByID(ctx, node_id);
17418
0
}
17419
17420
void ImGui::DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos)
17421
0
{
17422
0
    ImGuiContext* ctx = GImGui;
17423
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
17424
0
    if (node == NULL)
17425
0
        return;
17426
0
    node->Pos = pos;
17427
0
    node->AuthorityForPos = ImGuiDataAuthority_DockNode;
17428
0
}
17429
17430
void ImGui::DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size)
17431
0
{
17432
0
    ImGuiContext* ctx = GImGui;
17433
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
17434
0
    if (node == NULL)
17435
0
        return;
17436
0
    IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
17437
0
    node->Size = node->SizeRef = size;
17438
0
    node->AuthorityForSize = ImGuiDataAuthority_DockNode;
17439
0
}
17440
17441
// Make sure to use the ImGuiDockNodeFlags_DockSpace flag to create a dockspace node! Otherwise this will create a floating node!
17442
// - Floating node: you can then call DockBuilderSetNodePos()/DockBuilderSetNodeSize() to position and size the floating node.
17443
// - Dockspace node: calling DockBuilderSetNodePos() is unnecessary.
17444
// - If you intend to split a node immediately after creation using DockBuilderSplitNode(), make sure to call DockBuilderSetNodeSize() beforehand!
17445
//   For various reason, the splitting code currently needs a base size otherwise space may not be allocated as precisely as you would expect.
17446
// - Use (id == 0) to let the system allocate a node identifier.
17447
// - Existing node with a same id will be removed.
17448
ImGuiID ImGui::DockBuilderAddNode(ImGuiID id, ImGuiDockNodeFlags flags)
17449
0
{
17450
0
    ImGuiContext* ctx = GImGui;
17451
17452
0
    if (id != 0)
17453
0
        DockBuilderRemoveNode(id);
17454
17455
0
    ImGuiDockNode* node = NULL;
17456
0
    if (flags & ImGuiDockNodeFlags_DockSpace)
17457
0
    {
17458
0
        DockSpace(id, ImVec2(0, 0), (flags & ~ImGuiDockNodeFlags_DockSpace) | ImGuiDockNodeFlags_KeepAliveOnly);
17459
0
        node = DockContextFindNodeByID(ctx, id);
17460
0
    }
17461
0
    else
17462
0
    {
17463
0
        node = DockContextAddNode(ctx, id);
17464
0
        node->SetLocalFlags(flags);
17465
0
    }
17466
0
    node->LastFrameAlive = ctx->FrameCount;   // Set this otherwise BeginDocked will undock during the same frame.
17467
0
    return node->ID;
17468
0
}
17469
17470
void ImGui::DockBuilderRemoveNode(ImGuiID node_id)
17471
0
{
17472
0
    ImGuiContext* ctx = GImGui;
17473
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
17474
0
    if (node == NULL)
17475
0
        return;
17476
0
    DockBuilderRemoveNodeDockedWindows(node_id, true);
17477
0
    DockBuilderRemoveNodeChildNodes(node_id);
17478
    // Node may have moved or deleted if e.g. any merge happened
17479
0
    node = DockContextFindNodeByID(ctx, node_id);
17480
0
    if (node == NULL)
17481
0
        return;
17482
0
    if (node->IsCentralNode() && node->ParentNode)
17483
0
        node->ParentNode->SetLocalFlags(node->ParentNode->LocalFlags | ImGuiDockNodeFlags_CentralNode);
17484
0
    DockContextRemoveNode(ctx, node, true);
17485
0
}
17486
17487
// root_id = 0 to remove all, root_id != 0 to remove child of given node.
17488
void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id)
17489
0
{
17490
0
    ImGuiContext* ctx = GImGui;
17491
0
    ImGuiDockContext* dc  = &ctx->DockContext;
17492
17493
0
    ImGuiDockNode* root_node = root_id ? DockContextFindNodeByID(ctx, root_id) : NULL;
17494
0
    if (root_id && root_node == NULL)
17495
0
        return;
17496
0
    bool has_central_node = false;
17497
17498
0
    ImGuiDataAuthority backup_root_node_authority_for_pos = root_node ? root_node->AuthorityForPos : ImGuiDataAuthority_Auto;
17499
0
    ImGuiDataAuthority backup_root_node_authority_for_size = root_node ? root_node->AuthorityForSize : ImGuiDataAuthority_Auto;
17500
17501
    // Process active windows
17502
0
    ImVector<ImGuiDockNode*> nodes_to_remove;
17503
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
17504
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
17505
0
        {
17506
0
            bool want_removal = (root_id == 0) || (node->ID != root_id && DockNodeGetRootNode(node)->ID == root_id);
17507
0
            if (want_removal)
17508
0
            {
17509
0
                if (node->IsCentralNode())
17510
0
                    has_central_node = true;
17511
0
                if (root_id != 0)
17512
0
                    DockContextQueueNotifyRemovedNode(ctx, node);
17513
0
                if (root_node)
17514
0
                {
17515
0
                    DockNodeMoveWindows(root_node, node);
17516
0
                    DockSettingsRenameNodeReferences(node->ID, root_node->ID);
17517
0
                }
17518
0
                nodes_to_remove.push_back(node);
17519
0
            }
17520
0
        }
17521
17522
    // DockNodeMoveWindows->DockNodeAddWindow will normally set those when reaching two windows (which is only adequate during interactive merge)
17523
    // Make sure we don't lose our current pos/size. (FIXME-DOCK: Consider tidying up that code in DockNodeAddWindow instead)
17524
0
    if (root_node)
17525
0
    {
17526
0
        root_node->AuthorityForPos = backup_root_node_authority_for_pos;
17527
0
        root_node->AuthorityForSize = backup_root_node_authority_for_size;
17528
0
    }
17529
17530
    // Apply to settings
17531
0
    for (ImGuiWindowSettings* settings = ctx->SettingsWindows.begin(); settings != NULL; settings = ctx->SettingsWindows.next_chunk(settings))
17532
0
        if (ImGuiID window_settings_dock_id = settings->DockId)
17533
0
            for (int n = 0; n < nodes_to_remove.Size; n++)
17534
0
                if (nodes_to_remove[n]->ID == window_settings_dock_id)
17535
0
                {
17536
0
                    settings->DockId = root_id;
17537
0
                    break;
17538
0
                }
17539
17540
    // Not really efficient, but easier to destroy a whole hierarchy considering DockContextRemoveNode is attempting to merge nodes
17541
0
    if (nodes_to_remove.Size > 1)
17542
0
        ImQsort(nodes_to_remove.Data, nodes_to_remove.Size, sizeof(ImGuiDockNode*), DockNodeComparerDepthMostFirst);
17543
0
    for (int n = 0; n < nodes_to_remove.Size; n++)
17544
0
        DockContextRemoveNode(ctx, nodes_to_remove[n], false);
17545
17546
0
    if (root_id == 0)
17547
0
    {
17548
0
        dc->Nodes.Clear();
17549
0
        dc->Requests.clear();
17550
0
    }
17551
0
    else if (has_central_node)
17552
0
    {
17553
0
        root_node->CentralNode = root_node;
17554
0
        root_node->SetLocalFlags(root_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
17555
0
    }
17556
0
}
17557
17558
void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_settings_refs)
17559
0
{
17560
    // Clear references in settings
17561
0
    ImGuiContext* ctx = GImGui;
17562
0
    ImGuiContext& g = *ctx;
17563
0
    if (clear_settings_refs)
17564
0
    {
17565
0
        for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
17566
0
        {
17567
0
            bool want_removal = (root_id == 0) || (settings->DockId == root_id);
17568
0
            if (!want_removal && settings->DockId != 0)
17569
0
                if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, settings->DockId))
17570
0
                    if (DockNodeGetRootNode(node)->ID == root_id)
17571
0
                        want_removal = true;
17572
0
            if (want_removal)
17573
0
                settings->DockId = 0;
17574
0
        }
17575
0
    }
17576
17577
    // Clear references in windows
17578
0
    for (int n = 0; n < g.Windows.Size; n++)
17579
0
    {
17580
0
        ImGuiWindow* window = g.Windows[n];
17581
0
        bool want_removal = (root_id == 0) || (window->DockNode && DockNodeGetRootNode(window->DockNode)->ID == root_id) || (window->DockNodeAsHost && window->DockNodeAsHost->ID == root_id);
17582
0
        if (want_removal)
17583
0
        {
17584
0
            const ImGuiID backup_dock_id = window->DockId;
17585
0
            IM_UNUSED(backup_dock_id);
17586
0
            DockContextProcessUndockWindow(ctx, window, clear_settings_refs);
17587
0
            if (!clear_settings_refs)
17588
0
                IM_ASSERT(window->DockId == backup_dock_id);
17589
0
        }
17590
0
    }
17591
0
}
17592
17593
// If 'out_id_at_dir' or 'out_id_at_opposite_dir' are non NULL, the function will write out the ID of the two new nodes created.
17594
// Return value is ID of the node at the specified direction, so same as (*out_id_at_dir) if that pointer is set.
17595
// FIXME-DOCK: We are not exposing nor using split_outer.
17596
ImGuiID ImGui::DockBuilderSplitNode(ImGuiID id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_at_dir, ImGuiID* out_id_at_opposite_dir)
17597
0
{
17598
0
    ImGuiContext& g = *GImGui;
17599
0
    IM_ASSERT(split_dir != ImGuiDir_None);
17600
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderSplitNode: node 0x%08X, split_dir %d\n", id, split_dir);
17601
17602
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, id);
17603
0
    if (node == NULL)
17604
0
    {
17605
0
        IM_ASSERT(node != NULL);
17606
0
        return 0;
17607
0
    }
17608
17609
0
    IM_ASSERT(!node->IsSplitNode()); // Assert if already Split
17610
17611
0
    ImGuiDockRequest req;
17612
0
    req.Type = ImGuiDockRequestType_Split;
17613
0
    req.DockTargetWindow = NULL;
17614
0
    req.DockTargetNode = node;
17615
0
    req.DockPayload = NULL;
17616
0
    req.DockSplitDir = split_dir;
17617
0
    req.DockSplitRatio = ImSaturate((split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? size_ratio_for_node_at_dir : 1.0f - size_ratio_for_node_at_dir);
17618
0
    req.DockSplitOuter = false;
17619
0
    DockContextProcessDock(&g, &req);
17620
17621
0
    ImGuiID id_at_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 0 : 1]->ID;
17622
0
    ImGuiID id_at_opposite_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0]->ID;
17623
0
    if (out_id_at_dir)
17624
0
        *out_id_at_dir = id_at_dir;
17625
0
    if (out_id_at_opposite_dir)
17626
0
        *out_id_at_opposite_dir = id_at_opposite_dir;
17627
0
    return id_at_dir;
17628
0
}
17629
17630
static ImGuiDockNode* DockBuilderCopyNodeRec(ImGuiDockNode* src_node, ImGuiID dst_node_id_if_known, ImVector<ImGuiID>* out_node_remap_pairs)
17631
0
{
17632
0
    ImGuiContext& g = *GImGui;
17633
0
    ImGuiDockNode* dst_node = ImGui::DockContextAddNode(&g, dst_node_id_if_known);
17634
0
    dst_node->SharedFlags = src_node->SharedFlags;
17635
0
    dst_node->LocalFlags = src_node->LocalFlags;
17636
0
    dst_node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
17637
0
    dst_node->Pos = src_node->Pos;
17638
0
    dst_node->Size = src_node->Size;
17639
0
    dst_node->SizeRef = src_node->SizeRef;
17640
0
    dst_node->SplitAxis = src_node->SplitAxis;
17641
0
    dst_node->UpdateMergedFlags();
17642
17643
0
    out_node_remap_pairs->push_back(src_node->ID);
17644
0
    out_node_remap_pairs->push_back(dst_node->ID);
17645
17646
0
    for (int child_n = 0; child_n < IM_ARRAYSIZE(src_node->ChildNodes); child_n++)
17647
0
        if (src_node->ChildNodes[child_n])
17648
0
        {
17649
0
            dst_node->ChildNodes[child_n] = DockBuilderCopyNodeRec(src_node->ChildNodes[child_n], 0, out_node_remap_pairs);
17650
0
            dst_node->ChildNodes[child_n]->ParentNode = dst_node;
17651
0
        }
17652
17653
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] Fork node %08X -> %08X (%d childs)\n", src_node->ID, dst_node->ID, dst_node->IsSplitNode() ? 2 : 0);
17654
0
    return dst_node;
17655
0
}
17656
17657
void ImGui::DockBuilderCopyNode(ImGuiID src_node_id, ImGuiID dst_node_id, ImVector<ImGuiID>* out_node_remap_pairs)
17658
0
{
17659
0
    ImGuiContext* ctx = GImGui;
17660
0
    IM_ASSERT(src_node_id != 0);
17661
0
    IM_ASSERT(dst_node_id != 0);
17662
0
    IM_ASSERT(out_node_remap_pairs != NULL);
17663
17664
0
    DockBuilderRemoveNode(dst_node_id);
17665
17666
0
    ImGuiDockNode* src_node = DockContextFindNodeByID(ctx, src_node_id);
17667
0
    IM_ASSERT(src_node != NULL);
17668
17669
0
    out_node_remap_pairs->clear();
17670
0
    DockBuilderCopyNodeRec(src_node, dst_node_id, out_node_remap_pairs);
17671
17672
0
    IM_ASSERT((out_node_remap_pairs->Size % 2) == 0);
17673
0
}
17674
17675
void ImGui::DockBuilderCopyWindowSettings(const char* src_name, const char* dst_name)
17676
0
{
17677
0
    ImGuiWindow* src_window = FindWindowByName(src_name);
17678
0
    if (src_window == NULL)
17679
0
        return;
17680
0
    if (ImGuiWindow* dst_window = FindWindowByName(dst_name))
17681
0
    {
17682
0
        dst_window->Pos = src_window->Pos;
17683
0
        dst_window->Size = src_window->Size;
17684
0
        dst_window->SizeFull = src_window->SizeFull;
17685
0
        dst_window->Collapsed = src_window->Collapsed;
17686
0
    }
17687
0
    else if (ImGuiWindowSettings* dst_settings = FindOrCreateWindowSettings(dst_name))
17688
0
    {
17689
0
        ImVec2ih window_pos_2ih = ImVec2ih(src_window->Pos);
17690
0
        if (src_window->ViewportId != 0 && src_window->ViewportId != IMGUI_VIEWPORT_DEFAULT_ID)
17691
0
        {
17692
0
            dst_settings->ViewportPos = window_pos_2ih;
17693
0
            dst_settings->ViewportId = src_window->ViewportId;
17694
0
            dst_settings->Pos = ImVec2ih(0, 0);
17695
0
        }
17696
0
        else
17697
0
        {
17698
0
            dst_settings->Pos = window_pos_2ih;
17699
0
        }
17700
0
        dst_settings->Size = ImVec2ih(src_window->SizeFull);
17701
0
        dst_settings->Collapsed = src_window->Collapsed;
17702
0
    }
17703
0
}
17704
17705
// FIXME: Will probably want to change this signature, in particular how the window remapping pairs are passed.
17706
void ImGui::DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector<const char*>* in_window_remap_pairs)
17707
0
{
17708
0
    ImGuiContext& g = *GImGui;
17709
0
    IM_ASSERT(src_dockspace_id != 0);
17710
0
    IM_ASSERT(dst_dockspace_id != 0);
17711
0
    IM_ASSERT(in_window_remap_pairs != NULL);
17712
0
    IM_ASSERT((in_window_remap_pairs->Size % 2) == 0);
17713
17714
    // Duplicate entire dock
17715
    // FIXME: When overwriting dst_dockspace_id, windows that aren't part of our dockspace window class but that are docked in a same node will be split apart,
17716
    // whereas we could attempt to at least keep them together in a new, same floating node.
17717
0
    ImVector<ImGuiID> node_remap_pairs;
17718
0
    DockBuilderCopyNode(src_dockspace_id, dst_dockspace_id, &node_remap_pairs);
17719
17720
    // Attempt to transition all the upcoming windows associated to dst_dockspace_id into the newly created hierarchy of dock nodes
17721
    // (The windows associated to src_dockspace_id are staying in place)
17722
0
    ImVector<ImGuiID> src_windows;
17723
0
    for (int remap_window_n = 0; remap_window_n < in_window_remap_pairs->Size; remap_window_n += 2)
17724
0
    {
17725
0
        const char* src_window_name = (*in_window_remap_pairs)[remap_window_n];
17726
0
        const char* dst_window_name = (*in_window_remap_pairs)[remap_window_n + 1];
17727
0
        ImGuiID src_window_id = ImHashStr(src_window_name);
17728
0
        src_windows.push_back(src_window_id);
17729
17730
        // Search in the remapping tables
17731
0
        ImGuiID src_dock_id = 0;
17732
0
        if (ImGuiWindow* src_window = FindWindowByID(src_window_id))
17733
0
            src_dock_id = src_window->DockId;
17734
0
        else if (ImGuiWindowSettings* src_window_settings = FindWindowSettings(src_window_id))
17735
0
            src_dock_id = src_window_settings->DockId;
17736
0
        ImGuiID dst_dock_id = 0;
17737
0
        for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
17738
0
            if (node_remap_pairs[dock_remap_n] == src_dock_id)
17739
0
            {
17740
0
                dst_dock_id = node_remap_pairs[dock_remap_n + 1];
17741
                //node_remap_pairs[dock_remap_n] = node_remap_pairs[dock_remap_n + 1] = 0; // Clear
17742
0
                break;
17743
0
            }
17744
17745
0
        if (dst_dock_id != 0)
17746
0
        {
17747
            // Docked windows gets redocked into the new node hierarchy.
17748
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] Remap live window '%s' 0x%08X -> '%s' 0x%08X\n", src_window_name, src_dock_id, dst_window_name, dst_dock_id);
17749
0
            DockBuilderDockWindow(dst_window_name, dst_dock_id);
17750
0
        }
17751
0
        else
17752
0
        {
17753
            // Floating windows gets their settings transferred (regardless of whether the new window already exist or not)
17754
            // When this is leading to a Copy and not a Move, we would get two overlapping floating windows. Could we possibly dock them together?
17755
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window settings '%s' -> '%s'\n", src_window_name, dst_window_name);
17756
0
            DockBuilderCopyWindowSettings(src_window_name, dst_window_name);
17757
0
        }
17758
0
    }
17759
17760
    // Anything else in the source nodes of 'node_remap_pairs' are windows that are not included in the remapping list.
17761
    // Find those windows and move to them to the cloned dock node. This may be optional?
17762
    // Dock those are a second step as undocking would invalidate source dock nodes.
17763
0
    struct DockRemainingWindowTask { ImGuiWindow* Window; ImGuiID DockId; DockRemainingWindowTask(ImGuiWindow* window, ImGuiID dock_id) { Window = window; DockId = dock_id; } };
17764
0
    ImVector<DockRemainingWindowTask> dock_remaining_windows;
17765
0
    for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
17766
0
        if (ImGuiID src_dock_id = node_remap_pairs[dock_remap_n])
17767
0
        {
17768
0
            ImGuiID dst_dock_id = node_remap_pairs[dock_remap_n + 1];
17769
0
            ImGuiDockNode* node = DockBuilderGetNode(src_dock_id);
17770
0
            for (int window_n = 0; window_n < node->Windows.Size; window_n++)
17771
0
            {
17772
0
                ImGuiWindow* window = node->Windows[window_n];
17773
0
                if (src_windows.contains(window->ID))
17774
0
                    continue;
17775
17776
                // Docked windows gets redocked into the new node hierarchy.
17777
0
                IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window '%s' %08X -> %08X\n", window->Name, src_dock_id, dst_dock_id);
17778
0
                dock_remaining_windows.push_back(DockRemainingWindowTask(window, dst_dock_id));
17779
0
            }
17780
0
        }
17781
0
    for (const DockRemainingWindowTask& task : dock_remaining_windows)
17782
0
        DockBuilderDockWindow(task.Window->Name, task.DockId);
17783
0
}
17784
17785
// FIXME-DOCK: This is awkward because in series of split user is likely to loose access to its root node.
17786
void ImGui::DockBuilderFinish(ImGuiID root_id)
17787
0
{
17788
0
    ImGuiContext* ctx = GImGui;
17789
    //DockContextRebuild(ctx);
17790
0
    DockContextBuildAddWindowsToNodes(ctx, root_id);
17791
0
}
17792
17793
//-----------------------------------------------------------------------------
17794
// Docking: Begin/End Support Functions (called from Begin/End)
17795
//-----------------------------------------------------------------------------
17796
// - GetWindowAlwaysWantOwnTabBar()
17797
// - DockContextBindNodeToWindow()
17798
// - BeginDocked()
17799
// - BeginDockableDragDropSource()
17800
// - BeginDockableDragDropTarget()
17801
//-----------------------------------------------------------------------------
17802
17803
bool ImGui::GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window)
17804
9.00k
{
17805
9.00k
    ImGuiContext& g = *GImGui;
17806
9.00k
    if (g.IO.ConfigDockingAlwaysTabBar || window->WindowClass.DockingAlwaysTabBar)
17807
0
        if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking)) == 0)
17808
0
            if (!window->IsFallbackWindow)    // We don't support AlwaysTabBar on the fallback/implicit window to avoid unused dock-node overhead/noise
17809
0
                return true;
17810
9.00k
    return false;
17811
9.00k
}
17812
17813
static ImGuiDockNode* ImGui::DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window)
17814
0
{
17815
0
    ImGuiContext& g = *ctx;
17816
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
17817
0
    IM_ASSERT(window->DockNode == NULL);
17818
17819
    // We should not be docking into a split node (SetWindowDock should avoid this)
17820
0
    if (node && node->IsSplitNode())
17821
0
    {
17822
0
        DockContextProcessUndockWindow(ctx, window);
17823
0
        return NULL;
17824
0
    }
17825
17826
    // Create node
17827
0
    if (node == NULL)
17828
0
    {
17829
0
        node = DockContextAddNode(ctx, window->DockId);
17830
0
        node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
17831
0
        node->LastFrameAlive = g.FrameCount;
17832
0
    }
17833
17834
    // If the node just turned visible and is part of a hierarchy, it doesn't have a Size assigned by DockNodeTreeUpdatePosSize() yet,
17835
    // so we're forcing a Pos/Size update from the first ancestor that is already visible (often it will be the root node).
17836
    // If we don't do this, the window will be assigned a zero-size on its first frame, which won't ideally warm up the layout.
17837
    // This is a little wonky because we don't normally update the Pos/Size of visible node mid-frame.
17838
0
    if (!node->IsVisible)
17839
0
    {
17840
0
        ImGuiDockNode* ancestor_node = node;
17841
0
        while (!ancestor_node->IsVisible && ancestor_node->ParentNode)
17842
0
            ancestor_node = ancestor_node->ParentNode;
17843
0
        IM_ASSERT(ancestor_node->Size.x > 0.0f && ancestor_node->Size.y > 0.0f);
17844
0
        DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(ancestor_node));
17845
0
        DockNodeTreeUpdatePosSize(ancestor_node, ancestor_node->Pos, ancestor_node->Size, node);
17846
0
    }
17847
17848
    // Add window to node
17849
0
    bool node_was_visible = node->IsVisible;
17850
0
    DockNodeAddWindow(node, window, true);
17851
0
    node->IsVisible = node_was_visible; // Don't mark visible right away (so DockContextEndFrame() doesn't render it, maybe other side effects? will see)
17852
0
    IM_ASSERT(node == window->DockNode);
17853
0
    return node;
17854
0
}
17855
17856
void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open)
17857
0
{
17858
0
    ImGuiContext* ctx = GImGui;
17859
0
    ImGuiContext& g = *ctx;
17860
17861
    // Clear fields ahead so most early-out paths don't have to do it
17862
0
    window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
17863
17864
0
    const bool auto_dock_node = GetWindowAlwaysWantOwnTabBar(window);
17865
0
    if (auto_dock_node)
17866
0
    {
17867
0
        if (window->DockId == 0)
17868
0
        {
17869
0
            IM_ASSERT(window->DockNode == NULL);
17870
0
            window->DockId = DockContextGenNodeID(ctx);
17871
0
        }
17872
0
    }
17873
0
    else
17874
0
    {
17875
        // Calling SetNextWindowPos() undock windows by default (by setting PosUndock)
17876
0
        bool want_undock = false;
17877
0
        want_undock |= (window->Flags & ImGuiWindowFlags_NoDocking) != 0;
17878
0
        want_undock |= (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) && (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) && g.NextWindowData.PosUndock;
17879
0
        if (want_undock)
17880
0
        {
17881
0
            DockContextProcessUndockWindow(ctx, window);
17882
0
            return;
17883
0
        }
17884
0
    }
17885
17886
    // Bind to our dock node
17887
0
    ImGuiDockNode* node = window->DockNode;
17888
0
    if (node != NULL)
17889
0
        IM_ASSERT(window->DockId == node->ID);
17890
0
    if (window->DockId != 0 && node == NULL)
17891
0
    {
17892
0
        node = DockContextBindNodeToWindow(ctx, window);
17893
0
        if (node == NULL)
17894
0
            return;
17895
0
    }
17896
17897
#if 0
17898
    // Undock if the ImGuiDockNodeFlags_NoDockingInCentralNode got set
17899
    if (node->IsCentralNode && (node->Flags & ImGuiDockNodeFlags_NoDockingInCentralNode))
17900
    {
17901
        DockContextProcessUndockWindow(ctx, window);
17902
        return;
17903
    }
17904
#endif
17905
17906
    // Undock if our dockspace node disappeared
17907
    // Note how we are testing for LastFrameAlive and NOT LastFrameActive. A DockSpace node can be maintained alive while being inactive with ImGuiDockNodeFlags_KeepAliveOnly.
17908
0
    if (node->LastFrameAlive < g.FrameCount)
17909
0
    {
17910
        // If the window has been orphaned, transition the docknode to an implicit node processed in DockContextNewFrameUpdateDocking()
17911
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
17912
0
        if (root_node->LastFrameAlive < g.FrameCount)
17913
0
            DockContextProcessUndockWindow(ctx, window);
17914
0
        else
17915
0
            window->DockIsActive = true;
17916
0
        return;
17917
0
    }
17918
17919
    // Store style overrides
17920
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17921
0
        window->DockStyle.Colors[color_n] = ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
17922
17923
    // Fast path return. It is common for windows to hold on a persistent DockId but be the only visible window,
17924
    // and never create neither a host window neither a tab bar.
17925
    // FIXME-DOCK: replace ->HostWindow NULL compare with something more explicit (~was initially intended as a first frame test)
17926
0
    if (node->HostWindow == NULL)
17927
0
    {
17928
0
        if (node->State == ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing)
17929
0
            window->DockIsActive = true;
17930
0
        if (node->Windows.Size > 1)
17931
0
            DockNodeHideWindowDuringHostWindowCreation(window);
17932
0
        return;
17933
0
    }
17934
17935
    // We can have zero-sized nodes (e.g. children of a small-size dockspace)
17936
0
    IM_ASSERT(node->HostWindow);
17937
0
    IM_ASSERT(node->IsLeafNode());
17938
0
    IM_ASSERT(node->Size.x >= 0.0f && node->Size.y >= 0.0f);
17939
0
    node->State = ImGuiDockNodeState_HostWindowVisible;
17940
17941
    // Undock if we are submitted earlier than the host window
17942
0
    if (!(node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly) && window->BeginOrderWithinContext < node->HostWindow->BeginOrderWithinContext)
17943
0
    {
17944
0
        DockContextProcessUndockWindow(ctx, window);
17945
0
        return;
17946
0
    }
17947
17948
    // Position/Size window
17949
0
    SetNextWindowPos(node->Pos);
17950
0
    SetNextWindowSize(node->Size);
17951
0
    g.NextWindowData.PosUndock = false; // Cancel implicit undocking of SetNextWindowPos()
17952
0
    window->DockIsActive = true;
17953
0
    window->DockNodeIsVisible = true;
17954
0
    window->DockTabIsVisible = false;
17955
0
    if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
17956
0
        return;
17957
17958
    // When the window is selected we mark it as visible.
17959
0
    if (node->VisibleWindow == window)
17960
0
        window->DockTabIsVisible = true;
17961
17962
    // Update window flag
17963
0
    IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) == 0);
17964
0
    window->Flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_NoResize;
17965
0
    if (node->IsHiddenTabBar() || node->IsNoTabBar())
17966
0
        window->Flags |= ImGuiWindowFlags_NoTitleBar;
17967
0
    else
17968
0
        window->Flags &= ~ImGuiWindowFlags_NoTitleBar;      // Clear the NoTitleBar flag in case the user set it: confusingly enough we need a title bar height so we are correctly offset, but it won't be displayed!
17969
17970
    // Save new dock order only if the window has been visible once already
17971
    // This allows multiple windows to be created in the same frame and have their respective dock orders preserved.
17972
0
    if (node->TabBar && window->WasActive)
17973
0
        window->DockOrder = (short)DockNodeGetTabOrder(window);
17974
17975
0
    if ((node->WantCloseAll || node->WantCloseTabId == window->TabId) && p_open != NULL)
17976
0
        *p_open = false;
17977
17978
    // Update ChildId to allow returning from Child to Parent with Escape
17979
0
    ImGuiWindow* parent_window = window->DockNode->HostWindow;
17980
0
    window->ChildId = parent_window->GetID(window->Name);
17981
0
}
17982
17983
void ImGui::BeginDockableDragDropSource(ImGuiWindow* window)
17984
0
{
17985
0
    ImGuiContext& g = *GImGui;
17986
0
    IM_ASSERT(g.ActiveId == window->MoveId);
17987
0
    IM_ASSERT(g.MovingWindow == window);
17988
0
    IM_ASSERT(g.CurrentWindow == window);
17989
17990
0
    g.LastItemData.ID = window->MoveId;
17991
0
    window = window->RootWindowDockTree;
17992
0
    IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
17993
0
    bool is_drag_docking = (g.IO.ConfigDockingWithShift) || ImRect(0, 0, window->SizeFull.x, GetFrameHeight()).Contains(g.ActiveIdClickOffset); // FIXME-DOCKING: Need to make this stateful and explicit
17994
0
    if (is_drag_docking && BeginDragDropSource(ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers | ImGuiDragDropFlags_SourceAutoExpirePayload))
17995
0
    {
17996
0
        SetDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, &window, sizeof(window));
17997
0
        EndDragDropSource();
17998
17999
        // Store style overrides
18000
0
        for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
18001
0
            window->DockStyle.Colors[color_n] = ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
18002
0
    }
18003
0
}
18004
18005
void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window)
18006
0
{
18007
0
    ImGuiContext* ctx = GImGui;
18008
0
    ImGuiContext& g = *ctx;
18009
18010
    //IM_ASSERT(window->RootWindowDockTree == window); // May also be a DockSpace
18011
0
    IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
18012
0
    if (!g.DragDropActive)
18013
0
        return;
18014
    //GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
18015
0
    if (!BeginDragDropTargetCustom(window->Rect(), window->ID))
18016
0
        return;
18017
18018
    // Peek into the payload before calling AcceptDragDropPayload() so we can handle overlapping dock nodes with filtering
18019
    // (this is a little unusual pattern, normally most code would call AcceptDragDropPayload directly)
18020
0
    const ImGuiPayload* payload = &g.DragDropPayload;
18021
0
    if (!payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) || !DockNodeIsDropAllowed(window, *(ImGuiWindow**)payload->Data))
18022
0
    {
18023
0
        EndDragDropTarget();
18024
0
        return;
18025
0
    }
18026
18027
0
    ImGuiWindow* payload_window = *(ImGuiWindow**)payload->Data;
18028
0
    if (AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect))
18029
0
    {
18030
        // Select target node
18031
        // (Important: we cannot use g.HoveredDockNode here! Because each of our target node have filters based on payload, each candidate drop target will do its own evaluation)
18032
0
        bool dock_into_floating_window = false;
18033
0
        ImGuiDockNode* node = NULL;
18034
0
        if (window->DockNodeAsHost)
18035
0
        {
18036
            // Cannot assume that node will != NULL even though we passed the rectangle test: it depends on padding/spacing handled by DockNodeTreeFindVisibleNodeByPos().
18037
0
            node = DockNodeTreeFindVisibleNodeByPos(window->DockNodeAsHost, g.IO.MousePos);
18038
18039
            // There is an edge case when docking into a dockspace which only has _inactive_ nodes (because none of the windows are active)
18040
            // In this case we need to fallback into any leaf mode, possibly the central node.
18041
            // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first.
18042
0
            if (node && node->IsDockSpace() && node->IsRootNode())
18043
0
                node = (node->CentralNode && node->IsLeafNode()) ? node->CentralNode : DockNodeTreeFindFallbackLeafNode(node);
18044
0
        }
18045
0
        else
18046
0
        {
18047
0
            if (window->DockNode)
18048
0
                node = window->DockNode;
18049
0
            else
18050
0
                dock_into_floating_window = true; // Dock into a regular window
18051
0
        }
18052
18053
0
        const ImRect explicit_target_rect = (node && node->TabBar && !node->IsHiddenTabBar() && !node->IsNoTabBar()) ? node->TabBar->BarRect : ImRect(window->Pos, window->Pos + ImVec2(window->Size.x, GetFrameHeight()));
18054
0
        const bool is_explicit_target = g.IO.ConfigDockingWithShift || IsMouseHoveringRect(explicit_target_rect.Min, explicit_target_rect.Max);
18055
18056
        // Preview docking request and find out split direction/ratio
18057
        //const bool do_preview = true;     // Ignore testing for payload->IsPreview() which removes one frame of delay, but breaks overlapping drop targets within the same window.
18058
0
        const bool do_preview = payload->IsPreview() || payload->IsDelivery();
18059
0
        if (do_preview && (node != NULL || dock_into_floating_window))
18060
0
        {
18061
            // If we have a non-leaf node it means we are hovering the border of a parent node, in which case only outer markers will appear.
18062
0
            ImGuiDockPreviewData split_inner;
18063
0
            ImGuiDockPreviewData split_outer;
18064
0
            ImGuiDockPreviewData* split_data = &split_inner;
18065
0
            if (node && (node->ParentNode || node->IsCentralNode() || !node->IsLeafNode()))
18066
0
                if (ImGuiDockNode* root_node = DockNodeGetRootNode(node))
18067
0
                {
18068
0
                    DockNodePreviewDockSetup(window, root_node, payload_window, NULL, &split_outer, is_explicit_target, true);
18069
0
                    if (split_outer.IsSplitDirExplicit)
18070
0
                        split_data = &split_outer;
18071
0
                }
18072
0
            if (!node || node->IsLeafNode())
18073
0
                DockNodePreviewDockSetup(window, node, payload_window, NULL, &split_inner, is_explicit_target, false);
18074
0
            if (split_data == &split_outer)
18075
0
                split_inner.IsDropAllowed = false;
18076
18077
            // Draw inner then outer, so that previewed tab (in inner data) will be behind the outer drop boxes
18078
0
            DockNodePreviewDockRender(window, node, payload_window, &split_inner);
18079
0
            DockNodePreviewDockRender(window, node, payload_window, &split_outer);
18080
18081
            // Queue docking request
18082
0
            if (split_data->IsDropAllowed && payload->IsDelivery())
18083
0
                DockContextQueueDock(ctx, window, split_data->SplitNode, payload_window, split_data->SplitDir, split_data->SplitRatio, split_data == &split_outer);
18084
0
        }
18085
0
    }
18086
0
    EndDragDropTarget();
18087
0
}
18088
18089
//-----------------------------------------------------------------------------
18090
// Docking: Settings
18091
//-----------------------------------------------------------------------------
18092
// - DockSettingsRenameNodeReferences()
18093
// - DockSettingsRemoveNodeReferences()
18094
// - DockSettingsFindNodeSettings()
18095
// - DockSettingsHandler_ApplyAll()
18096
// - DockSettingsHandler_ReadOpen()
18097
// - DockSettingsHandler_ReadLine()
18098
// - DockSettingsHandler_DockNodeToSettings()
18099
// - DockSettingsHandler_WriteAll()
18100
//-----------------------------------------------------------------------------
18101
18102
static void ImGui::DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id)
18103
0
{
18104
0
    ImGuiContext& g = *GImGui;
18105
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockSettingsRenameNodeReferences: from 0x%08X -> to 0x%08X\n", old_node_id, new_node_id);
18106
0
    for (int window_n = 0; window_n < g.Windows.Size; window_n++)
18107
0
    {
18108
0
        ImGuiWindow* window = g.Windows[window_n];
18109
0
        if (window->DockId == old_node_id && window->DockNode == NULL)
18110
0
            window->DockId = new_node_id;
18111
0
    }
18112
    //// FIXME-OPT: We could remove this loop by storing the index in the map
18113
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18114
0
        if (settings->DockId == old_node_id)
18115
0
            settings->DockId = new_node_id;
18116
0
}
18117
18118
// Remove references stored in ImGuiWindowSettings to the given ImGuiDockNodeSettings
18119
static void ImGui::DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count)
18120
0
{
18121
0
    ImGuiContext& g = *GImGui;
18122
0
    int found = 0;
18123
    //// FIXME-OPT: We could remove this loop by storing the index in the map
18124
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18125
0
        for (int node_n = 0; node_n < node_ids_count; node_n++)
18126
0
            if (settings->DockId == node_ids[node_n])
18127
0
            {
18128
0
                settings->DockId = 0;
18129
0
                settings->DockOrder = -1;
18130
0
                if (++found < node_ids_count)
18131
0
                    break;
18132
0
                return;
18133
0
            }
18134
0
}
18135
18136
static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID id)
18137
0
{
18138
    // FIXME-OPT
18139
0
    ImGuiDockContext* dc  = &ctx->DockContext;
18140
0
    for (int n = 0; n < dc->NodesSettings.Size; n++)
18141
0
        if (dc->NodesSettings[n].ID == id)
18142
0
            return &dc->NodesSettings[n];
18143
0
    return NULL;
18144
0
}
18145
18146
// Clear settings data
18147
static void ImGui::DockSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
18148
0
{
18149
0
    ImGuiDockContext* dc  = &ctx->DockContext;
18150
0
    dc->NodesSettings.clear();
18151
0
    DockContextClearNodes(ctx, 0, true);
18152
0
}
18153
18154
// Recreate nodes based on settings data
18155
static void ImGui::DockSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
18156
0
{
18157
    // Prune settings at boot time only
18158
0
    ImGuiDockContext* dc  = &ctx->DockContext;
18159
0
    if (ctx->Windows.Size == 0)
18160
0
        DockContextPruneUnusedSettingsNodes(ctx);
18161
0
    DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
18162
0
    DockContextBuildAddWindowsToNodes(ctx, 0);
18163
0
}
18164
18165
static void* ImGui::DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
18166
0
{
18167
0
    if (strcmp(name, "Data") != 0)
18168
0
        return NULL;
18169
0
    return (void*)1;
18170
0
}
18171
18172
static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettingsHandler*, void*, const char* line)
18173
0
{
18174
0
    char c = 0;
18175
0
    int x = 0, y = 0;
18176
0
    int r = 0;
18177
18178
    // Parsing, e.g.
18179
    // " DockNode   ID=0x00000001 Pos=383,193 Size=201,322 Split=Y,0.506 "
18180
    // "   DockNode ID=0x00000002 Parent=0x00000001 "
18181
    // Important: this code expect currently fields in a fixed order.
18182
0
    ImGuiDockNodeSettings node;
18183
0
    line = ImStrSkipBlank(line);
18184
0
    if      (strncmp(line, "DockNode", 8) == 0)  { line = ImStrSkipBlank(line + strlen("DockNode")); }
18185
0
    else if (strncmp(line, "DockSpace", 9) == 0) { line = ImStrSkipBlank(line + strlen("DockSpace")); node.Flags |= ImGuiDockNodeFlags_DockSpace; }
18186
0
    else return;
18187
0
    if (sscanf(line, "ID=0x%08X%n",      &node.ID, &r) == 1)            { line += r; } else return;
18188
0
    if (sscanf(line, " Parent=0x%08X%n", &node.ParentNodeId, &r) == 1)  { line += r; if (node.ParentNodeId == 0) return; }
18189
0
    if (sscanf(line, " Window=0x%08X%n", &node.ParentWindowId, &r) ==1) { line += r; if (node.ParentWindowId == 0) return; }
18190
0
    if (node.ParentNodeId == 0)
18191
0
    {
18192
0
        if (sscanf(line, " Pos=%i,%i%n",  &x, &y, &r) == 2)         { line += r; node.Pos = ImVec2ih((short)x, (short)y); } else return;
18193
0
        if (sscanf(line, " Size=%i,%i%n", &x, &y, &r) == 2)         { line += r; node.Size = ImVec2ih((short)x, (short)y); } else return;
18194
0
    }
18195
0
    else
18196
0
    {
18197
0
        if (sscanf(line, " SizeRef=%i,%i%n", &x, &y, &r) == 2)      { line += r; node.SizeRef = ImVec2ih((short)x, (short)y); }
18198
0
    }
18199
0
    if (sscanf(line, " Split=%c%n", &c, &r) == 1)                   { line += r; if (c == 'X') node.SplitAxis = ImGuiAxis_X; else if (c == 'Y') node.SplitAxis = ImGuiAxis_Y; }
18200
0
    if (sscanf(line, " NoResize=%d%n", &x, &r) == 1)                { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoResize; }
18201
0
    if (sscanf(line, " CentralNode=%d%n", &x, &r) == 1)             { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_CentralNode; }
18202
0
    if (sscanf(line, " NoTabBar=%d%n", &x, &r) == 1)                { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoTabBar; }
18203
0
    if (sscanf(line, " HiddenTabBar=%d%n", &x, &r) == 1)            { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_HiddenTabBar; }
18204
0
    if (sscanf(line, " NoWindowMenuButton=%d%n", &x, &r) == 1)      { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoWindowMenuButton; }
18205
0
    if (sscanf(line, " NoCloseButton=%d%n", &x, &r) == 1)           { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoCloseButton; }
18206
0
    if (sscanf(line, " Selected=0x%08X%n", &node.SelectedTabId,&r) == 1) { line += r; }
18207
0
    if (node.ParentNodeId != 0)
18208
0
        if (ImGuiDockNodeSettings* parent_settings = DockSettingsFindNodeSettings(ctx, node.ParentNodeId))
18209
0
            node.Depth = parent_settings->Depth + 1;
18210
0
    ctx->DockContext.NodesSettings.push_back(node);
18211
0
}
18212
18213
static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDockNode* node, int depth)
18214
0
{
18215
0
    ImGuiDockNodeSettings node_settings;
18216
0
    IM_ASSERT(depth < (1 << (sizeof(node_settings.Depth) << 3)));
18217
0
    node_settings.ID = node->ID;
18218
0
    node_settings.ParentNodeId = node->ParentNode ? node->ParentNode->ID : 0;
18219
0
    node_settings.ParentWindowId = (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow) ? node->HostWindow->ParentWindow->ID : 0;
18220
0
    node_settings.SelectedTabId = node->SelectedTabId;
18221
0
    node_settings.SplitAxis = (signed char)(node->IsSplitNode() ? node->SplitAxis : ImGuiAxis_None);
18222
0
    node_settings.Depth = (char)depth;
18223
0
    node_settings.Flags = (node->LocalFlags & ImGuiDockNodeFlags_SavedFlagsMask_);
18224
0
    node_settings.Pos = ImVec2ih(node->Pos);
18225
0
    node_settings.Size = ImVec2ih(node->Size);
18226
0
    node_settings.SizeRef = ImVec2ih(node->SizeRef);
18227
0
    dc->NodesSettings.push_back(node_settings);
18228
0
    if (node->ChildNodes[0])
18229
0
        DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[0], depth + 1);
18230
0
    if (node->ChildNodes[1])
18231
0
        DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[1], depth + 1);
18232
0
}
18233
18234
static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
18235
0
{
18236
0
    ImGuiContext& g = *ctx;
18237
0
    ImGuiDockContext* dc = &ctx->DockContext;
18238
0
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
18239
0
        return;
18240
18241
    // Gather settings data
18242
    // (unlike our windows settings, because nodes are always built we can do a full rewrite of the SettingsNode buffer)
18243
0
    dc->NodesSettings.resize(0);
18244
0
    dc->NodesSettings.reserve(dc->Nodes.Data.Size);
18245
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
18246
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
18247
0
            if (node->IsRootNode())
18248
0
                DockSettingsHandler_DockNodeToSettings(dc, node, 0);
18249
18250
0
    int max_depth = 0;
18251
0
    for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
18252
0
        max_depth = ImMax((int)dc->NodesSettings[node_n].Depth, max_depth);
18253
18254
    // Write to text buffer
18255
0
    buf->appendf("[%s][Data]\n", handler->TypeName);
18256
0
    for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
18257
0
    {
18258
0
        const int line_start_pos = buf->size(); (void)line_start_pos;
18259
0
        const ImGuiDockNodeSettings* node_settings = &dc->NodesSettings[node_n];
18260
0
        buf->appendf("%*s%s%*s", node_settings->Depth * 2, "", (node_settings->Flags & ImGuiDockNodeFlags_DockSpace) ? "DockSpace" : "DockNode ", (max_depth - node_settings->Depth) * 2, "");  // Text align nodes to facilitate looking at .ini file
18261
0
        buf->appendf(" ID=0x%08X", node_settings->ID);
18262
0
        if (node_settings->ParentNodeId)
18263
0
        {
18264
0
            buf->appendf(" Parent=0x%08X SizeRef=%d,%d", node_settings->ParentNodeId, node_settings->SizeRef.x, node_settings->SizeRef.y);
18265
0
        }
18266
0
        else
18267
0
        {
18268
0
            if (node_settings->ParentWindowId)
18269
0
                buf->appendf(" Window=0x%08X", node_settings->ParentWindowId);
18270
0
            buf->appendf(" Pos=%d,%d Size=%d,%d", node_settings->Pos.x, node_settings->Pos.y, node_settings->Size.x, node_settings->Size.y);
18271
0
        }
18272
0
        if (node_settings->SplitAxis != ImGuiAxis_None)
18273
0
            buf->appendf(" Split=%c", (node_settings->SplitAxis == ImGuiAxis_X) ? 'X' : 'Y');
18274
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoResize)
18275
0
            buf->appendf(" NoResize=1");
18276
0
        if (node_settings->Flags & ImGuiDockNodeFlags_CentralNode)
18277
0
            buf->appendf(" CentralNode=1");
18278
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoTabBar)
18279
0
            buf->appendf(" NoTabBar=1");
18280
0
        if (node_settings->Flags & ImGuiDockNodeFlags_HiddenTabBar)
18281
0
            buf->appendf(" HiddenTabBar=1");
18282
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoWindowMenuButton)
18283
0
            buf->appendf(" NoWindowMenuButton=1");
18284
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoCloseButton)
18285
0
            buf->appendf(" NoCloseButton=1");
18286
0
        if (node_settings->SelectedTabId)
18287
0
            buf->appendf(" Selected=0x%08X", node_settings->SelectedTabId);
18288
18289
#if IMGUI_DEBUG_INI_SETTINGS
18290
        // [DEBUG] Include comments in the .ini file to ease debugging
18291
        if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_settings->ID))
18292
        {
18293
            buf->appendf("%*s", ImMax(2, (line_start_pos + 92) - buf->size()), "");     // Align everything
18294
            if (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow)
18295
                buf->appendf(" ; in '%s'", node->HostWindow->ParentWindow->Name);
18296
            // Iterate settings so we can give info about windows that didn't exist during the session.
18297
            int contains_window = 0;
18298
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18299
                if (settings->DockId == node_settings->ID)
18300
                {
18301
                    if (contains_window++ == 0)
18302
                        buf->appendf(" ; contains ");
18303
                    buf->appendf("'%s' ", settings->GetName());
18304
                }
18305
        }
18306
#endif
18307
0
        buf->appendf("\n");
18308
0
    }
18309
0
    buf->appendf("\n");
18310
0
}
18311
18312
18313
//-----------------------------------------------------------------------------
18314
// [SECTION] PLATFORM DEPENDENT HELPERS
18315
//-----------------------------------------------------------------------------
18316
18317
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
18318
18319
#ifdef _MSC_VER
18320
#pragma comment(lib, "user32")
18321
#pragma comment(lib, "kernel32")
18322
#endif
18323
18324
// Win32 clipboard implementation
18325
// We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown()
18326
static const char* GetClipboardTextFn_DefaultImpl(void*)
18327
{
18328
    ImGuiContext& g = *GImGui;
18329
    g.ClipboardHandlerData.clear();
18330
    if (!::OpenClipboard(NULL))
18331
        return NULL;
18332
    HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
18333
    if (wbuf_handle == NULL)
18334
    {
18335
        ::CloseClipboard();
18336
        return NULL;
18337
    }
18338
    if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle))
18339
    {
18340
        int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL);
18341
        g.ClipboardHandlerData.resize(buf_len);
18342
        ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, g.ClipboardHandlerData.Data, buf_len, NULL, NULL);
18343
    }
18344
    ::GlobalUnlock(wbuf_handle);
18345
    ::CloseClipboard();
18346
    return g.ClipboardHandlerData.Data;
18347
}
18348
18349
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
18350
{
18351
    if (!::OpenClipboard(NULL))
18352
        return;
18353
    const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
18354
    HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR));
18355
    if (wbuf_handle == NULL)
18356
    {
18357
        ::CloseClipboard();
18358
        return;
18359
    }
18360
    WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle);
18361
    ::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length);
18362
    ::GlobalUnlock(wbuf_handle);
18363
    ::EmptyClipboard();
18364
    if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
18365
        ::GlobalFree(wbuf_handle);
18366
    ::CloseClipboard();
18367
}
18368
18369
#elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
18370
18371
#include <Carbon/Carbon.h>  // Use old API to avoid need for separate .mm file
18372
static PasteboardRef main_clipboard = 0;
18373
18374
// OSX clipboard implementation
18375
// If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!
18376
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
18377
{
18378
    if (!main_clipboard)
18379
        PasteboardCreate(kPasteboardClipboard, &main_clipboard);
18380
    PasteboardClear(main_clipboard);
18381
    CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text));
18382
    if (cf_data)
18383
    {
18384
        PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
18385
        CFRelease(cf_data);
18386
    }
18387
}
18388
18389
static const char* GetClipboardTextFn_DefaultImpl(void*)
18390
{
18391
    if (!main_clipboard)
18392
        PasteboardCreate(kPasteboardClipboard, &main_clipboard);
18393
    PasteboardSynchronize(main_clipboard);
18394
18395
    ItemCount item_count = 0;
18396
    PasteboardGetItemCount(main_clipboard, &item_count);
18397
    for (ItemCount i = 0; i < item_count; i++)
18398
    {
18399
        PasteboardItemID item_id = 0;
18400
        PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);
18401
        CFArrayRef flavor_type_array = 0;
18402
        PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);
18403
        for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)
18404
        {
18405
            CFDataRef cf_data;
18406
            if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
18407
            {
18408
                ImGuiContext& g = *GImGui;
18409
                g.ClipboardHandlerData.clear();
18410
                int length = (int)CFDataGetLength(cf_data);
18411
                g.ClipboardHandlerData.resize(length + 1);
18412
                CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)g.ClipboardHandlerData.Data);
18413
                g.ClipboardHandlerData[length] = 0;
18414
                CFRelease(cf_data);
18415
                return g.ClipboardHandlerData.Data;
18416
            }
18417
        }
18418
    }
18419
    return NULL;
18420
}
18421
18422
#else
18423
18424
// Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.
18425
static const char* GetClipboardTextFn_DefaultImpl(void*)
18426
0
{
18427
0
    ImGuiContext& g = *GImGui;
18428
0
    return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin();
18429
0
}
18430
18431
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
18432
0
{
18433
0
    ImGuiContext& g = *GImGui;
18434
0
    g.ClipboardHandlerData.clear();
18435
0
    const char* text_end = text + strlen(text);
18436
0
    g.ClipboardHandlerData.resize((int)(text_end - text) + 1);
18437
0
    memcpy(&g.ClipboardHandlerData[0], text, (size_t)(text_end - text));
18438
0
    g.ClipboardHandlerData[(int)(text_end - text)] = 0;
18439
0
}
18440
18441
#endif
18442
18443
// Win32 API IME support (for Asian languages, etc.)
18444
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
18445
18446
#include <imm.h>
18447
#ifdef _MSC_VER
18448
#pragma comment(lib, "imm32")
18449
#endif
18450
18451
static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data)
18452
{
18453
    // Notify OS Input Method Editor of text input position
18454
    HWND hwnd = (HWND)viewport->PlatformHandleRaw;
18455
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
18456
    if (hwnd == 0)
18457
        hwnd = (HWND)ImGui::GetIO().ImeWindowHandle;
18458
#endif
18459
    if (hwnd == 0)
18460
        return;
18461
18462
    //::ImmAssociateContextEx(hwnd, NULL, data->WantVisible ? IACE_DEFAULT : 0);
18463
    if (HIMC himc = ::ImmGetContext(hwnd))
18464
    {
18465
        COMPOSITIONFORM composition_form = {};
18466
        composition_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
18467
        composition_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
18468
        composition_form.dwStyle = CFS_FORCE_POSITION;
18469
        ::ImmSetCompositionWindow(himc, &composition_form);
18470
        CANDIDATEFORM candidate_form = {};
18471
        candidate_form.dwStyle = CFS_CANDIDATEPOS;
18472
        candidate_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
18473
        candidate_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
18474
        ::ImmSetCandidateWindow(himc, &candidate_form);
18475
        ::ImmReleaseContext(hwnd, himc);
18476
    }
18477
}
18478
18479
#else
18480
18481
0
static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport*, ImGuiPlatformImeData*) {}
18482
18483
#endif
18484
18485
//-----------------------------------------------------------------------------
18486
// [SECTION] METRICS/DEBUGGER WINDOW
18487
//-----------------------------------------------------------------------------
18488
// - RenderViewportThumbnail() [Internal]
18489
// - RenderViewportsThumbnails() [Internal]
18490
// - DebugTextEncoding()
18491
// - MetricsHelpMarker() [Internal]
18492
// - ShowFontAtlas() [Internal]
18493
// - ShowMetricsWindow()
18494
// - DebugNodeColumns() [Internal]
18495
// - DebugNodeDockNode() [Internal]
18496
// - DebugNodeDrawList() [Internal]
18497
// - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal]
18498
// - DebugNodeFont() [Internal]
18499
// - DebugNodeFontGlyph() [Internal]
18500
// - DebugNodeStorage() [Internal]
18501
// - DebugNodeTabBar() [Internal]
18502
// - DebugNodeViewport() [Internal]
18503
// - DebugNodeWindow() [Internal]
18504
// - DebugNodeWindowSettings() [Internal]
18505
// - DebugNodeWindowsList() [Internal]
18506
// - DebugNodeWindowsListByBeginStackParent() [Internal]
18507
//-----------------------------------------------------------------------------
18508
18509
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
18510
18511
void ImGui::DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb)
18512
0
{
18513
0
    ImGuiContext& g = *GImGui;
18514
0
    ImGuiWindow* window = g.CurrentWindow;
18515
18516
0
    ImVec2 scale = bb.GetSize() / viewport->Size;
18517
0
    ImVec2 off = bb.Min - viewport->Pos * scale;
18518
0
    float alpha_mul = (viewport->Flags & ImGuiViewportFlags_Minimized) ? 0.30f : 1.00f;
18519
0
    window->DrawList->AddRectFilled(bb.Min, bb.Max, ImGui::GetColorU32(ImGuiCol_Border, alpha_mul * 0.40f));
18520
0
    for (int i = 0; i != g.Windows.Size; i++)
18521
0
    {
18522
0
        ImGuiWindow* thumb_window = g.Windows[i];
18523
0
        if (!thumb_window->WasActive || (thumb_window->Flags & ImGuiWindowFlags_ChildWindow))
18524
0
            continue;
18525
0
        if (thumb_window->Viewport != viewport)
18526
0
            continue;
18527
18528
0
        ImRect thumb_r = thumb_window->Rect();
18529
0
        ImRect title_r = thumb_window->TitleBarRect();
18530
0
        thumb_r = ImRect(ImFloor(off + thumb_r.Min * scale), ImFloor(off +  thumb_r.Max * scale));
18531
0
        title_r = ImRect(ImFloor(off + title_r.Min * scale), ImFloor(off +  ImVec2(title_r.Max.x, title_r.Min.y) * scale) + ImVec2(0,5)); // Exaggerate title bar height
18532
0
        thumb_r.ClipWithFull(bb);
18533
0
        title_r.ClipWithFull(bb);
18534
0
        const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
18535
0
        window->DrawList->AddRectFilled(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_WindowBg, alpha_mul));
18536
0
        window->DrawList->AddRectFilled(title_r.Min, title_r.Max, GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul));
18537
0
        window->DrawList->AddRect(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
18538
0
        window->DrawList->AddText(g.Font, g.FontSize * 1.0f, title_r.Min, GetColorU32(ImGuiCol_Text, alpha_mul), thumb_window->Name, FindRenderedTextEnd(thumb_window->Name));
18539
0
    }
18540
0
    draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
18541
0
}
18542
18543
static void RenderViewportsThumbnails()
18544
0
{
18545
0
    ImGuiContext& g = *GImGui;
18546
0
    ImGuiWindow* window = g.CurrentWindow;
18547
18548
    // We don't display full monitor bounds (we could, but it often looks awkward), instead we display just enough to cover all of our viewports.
18549
0
    float SCALE = 1.0f / 8.0f;
18550
0
    ImRect bb_full(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
18551
0
    for (int n = 0; n < g.Viewports.Size; n++)
18552
0
        bb_full.Add(g.Viewports[n]->GetMainRect());
18553
0
    ImVec2 p = window->DC.CursorPos;
18554
0
    ImVec2 off = p - bb_full.Min * SCALE;
18555
0
    for (int n = 0; n < g.Viewports.Size; n++)
18556
0
    {
18557
0
        ImGuiViewportP* viewport = g.Viewports[n];
18558
0
        ImRect viewport_draw_bb(off + (viewport->Pos) * SCALE, off + (viewport->Pos + viewport->Size) * SCALE);
18559
0
        ImGui::DebugRenderViewportThumbnail(window->DrawList, viewport, viewport_draw_bb);
18560
0
    }
18561
0
    ImGui::Dummy(bb_full.GetSize() * SCALE);
18562
0
}
18563
18564
static int IMGUI_CDECL ViewportComparerByFrontMostStampCount(const void* lhs, const void* rhs)
18565
0
{
18566
0
    const ImGuiViewportP* a = *(const ImGuiViewportP* const*)lhs;
18567
0
    const ImGuiViewportP* b = *(const ImGuiViewportP* const*)rhs;
18568
0
    return b->LastFrontMostStampCount - a->LastFrontMostStampCount;
18569
0
}
18570
18571
// Draw an arbitrary US keyboard layout to visualize translated keys
18572
void ImGui::DebugRenderKeyboardPreview(ImDrawList* draw_list)
18573
0
{
18574
0
    const ImVec2 key_size = ImVec2(35.0f, 35.0f);
18575
0
    const float  key_rounding = 3.0f;
18576
0
    const ImVec2 key_face_size = ImVec2(25.0f, 25.0f);
18577
0
    const ImVec2 key_face_pos = ImVec2(5.0f, 3.0f);
18578
0
    const float  key_face_rounding = 2.0f;
18579
0
    const ImVec2 key_label_pos = ImVec2(7.0f, 4.0f);
18580
0
    const ImVec2 key_step = ImVec2(key_size.x - 1.0f, key_size.y - 1.0f);
18581
0
    const float  key_row_offset = 9.0f;
18582
18583
0
    ImVec2 board_min = GetCursorScreenPos();
18584
0
    ImVec2 board_max = ImVec2(board_min.x + 3 * key_step.x + 2 * key_row_offset + 10.0f, board_min.y + 3 * key_step.y + 10.0f);
18585
0
    ImVec2 start_pos = ImVec2(board_min.x + 5.0f - key_step.x, board_min.y);
18586
18587
0
    struct KeyLayoutData { int Row, Col; const char* Label; ImGuiKey Key; };
18588
0
    const KeyLayoutData keys_to_display[] =
18589
0
    {
18590
0
        { 0, 0, "", ImGuiKey_Tab },      { 0, 1, "Q", ImGuiKey_Q }, { 0, 2, "W", ImGuiKey_W }, { 0, 3, "E", ImGuiKey_E }, { 0, 4, "R", ImGuiKey_R },
18591
0
        { 1, 0, "", ImGuiKey_CapsLock }, { 1, 1, "A", ImGuiKey_A }, { 1, 2, "S", ImGuiKey_S }, { 1, 3, "D", ImGuiKey_D }, { 1, 4, "F", ImGuiKey_F },
18592
0
        { 2, 0, "", ImGuiKey_LeftShift },{ 2, 1, "Z", ImGuiKey_Z }, { 2, 2, "X", ImGuiKey_X }, { 2, 3, "C", ImGuiKey_C }, { 2, 4, "V", ImGuiKey_V }
18593
0
    };
18594
18595
    // Elements rendered manually via ImDrawList API are not clipped automatically.
18596
    // While not strictly necessary, here IsItemVisible() is used to avoid rendering these shapes when they are out of view.
18597
0
    Dummy(board_max - board_min);
18598
0
    if (!IsItemVisible())
18599
0
        return;
18600
0
    draw_list->PushClipRect(board_min, board_max, true);
18601
0
    for (int n = 0; n < IM_ARRAYSIZE(keys_to_display); n++)
18602
0
    {
18603
0
        const KeyLayoutData* key_data = &keys_to_display[n];
18604
0
        ImVec2 key_min = ImVec2(start_pos.x + key_data->Col * key_step.x + key_data->Row * key_row_offset, start_pos.y + key_data->Row * key_step.y);
18605
0
        ImVec2 key_max = key_min + key_size;
18606
0
        draw_list->AddRectFilled(key_min, key_max, IM_COL32(204, 204, 204, 255), key_rounding);
18607
0
        draw_list->AddRect(key_min, key_max, IM_COL32(24, 24, 24, 255), key_rounding);
18608
0
        ImVec2 face_min = ImVec2(key_min.x + key_face_pos.x, key_min.y + key_face_pos.y);
18609
0
        ImVec2 face_max = ImVec2(face_min.x + key_face_size.x, face_min.y + key_face_size.y);
18610
0
        draw_list->AddRect(face_min, face_max, IM_COL32(193, 193, 193, 255), key_face_rounding, ImDrawFlags_None, 2.0f);
18611
0
        draw_list->AddRectFilled(face_min, face_max, IM_COL32(252, 252, 252, 255), key_face_rounding);
18612
0
        ImVec2 label_min = ImVec2(key_min.x + key_label_pos.x, key_min.y + key_label_pos.y);
18613
0
        draw_list->AddText(label_min, IM_COL32(64, 64, 64, 255), key_data->Label);
18614
0
        if (ImGui::IsKeyDown(key_data->Key))
18615
0
            draw_list->AddRectFilled(key_min, key_max, IM_COL32(255, 0, 0, 128), key_rounding);
18616
0
    }
18617
0
    draw_list->PopClipRect();
18618
0
}
18619
18620
// Helper tool to diagnose between text encoding issues and font loading issues. Pass your UTF-8 string and verify that there are correct.
18621
void ImGui::DebugTextEncoding(const char* str)
18622
0
{
18623
0
    Text("Text: \"%s\"", str);
18624
0
    if (!BeginTable("list", 4, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit))
18625
0
        return;
18626
0
    TableSetupColumn("Offset");
18627
0
    TableSetupColumn("UTF-8");
18628
0
    TableSetupColumn("Glyph");
18629
0
    TableSetupColumn("Codepoint");
18630
0
    TableHeadersRow();
18631
0
    for (const char* p = str; *p != 0; )
18632
0
    {
18633
0
        unsigned int c;
18634
0
        const int c_utf8_len = ImTextCharFromUtf8(&c, p, NULL);
18635
0
        TableNextColumn();
18636
0
        Text("%d", (int)(p - str));
18637
0
        TableNextColumn();
18638
0
        for (int byte_index = 0; byte_index < c_utf8_len; byte_index++)
18639
0
        {
18640
0
            if (byte_index > 0)
18641
0
                SameLine();
18642
0
            Text("0x%02X", (int)(unsigned char)p[byte_index]);
18643
0
        }
18644
0
        TableNextColumn();
18645
0
        if (GetFont()->FindGlyphNoFallback((ImWchar)c))
18646
0
            TextUnformatted(p, p + c_utf8_len);
18647
0
        else
18648
0
            TextUnformatted((c == IM_UNICODE_CODEPOINT_INVALID) ? "[invalid]" : "[missing]");
18649
0
        TableNextColumn();
18650
0
        Text("U+%04X", (int)c);
18651
0
        p += c_utf8_len;
18652
0
    }
18653
0
    EndTable();
18654
0
}
18655
18656
// Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
18657
static void MetricsHelpMarker(const char* desc)
18658
0
{
18659
0
    ImGui::TextDisabled("(?)");
18660
0
    if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayShort))
18661
0
    {
18662
0
        ImGui::BeginTooltip();
18663
0
        ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
18664
0
        ImGui::TextUnformatted(desc);
18665
0
        ImGui::PopTextWrapPos();
18666
0
        ImGui::EndTooltip();
18667
0
    }
18668
0
}
18669
18670
// [DEBUG] List fonts in a font atlas and display its texture
18671
void ImGui::ShowFontAtlas(ImFontAtlas* atlas)
18672
0
{
18673
0
    for (int i = 0; i < atlas->Fonts.Size; i++)
18674
0
    {
18675
0
        ImFont* font = atlas->Fonts[i];
18676
0
        PushID(font);
18677
0
        DebugNodeFont(font);
18678
0
        PopID();
18679
0
    }
18680
0
    if (TreeNode("Font Atlas", "Font Atlas (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight))
18681
0
    {
18682
0
        ImGuiContext& g = *GImGui;
18683
0
        ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
18684
0
        Checkbox("Tint with Text Color", &cfg->ShowAtlasTintedWithTextColor); // Using text color ensure visibility of core atlas data, but will alter custom colored icons
18685
0
        ImVec4 tint_col = cfg->ShowAtlasTintedWithTextColor ? GetStyleColorVec4(ImGuiCol_Text) : ImVec4(1.0f, 1.0f, 1.0f, 1.0f);
18686
0
        ImVec4 border_col = GetStyleColorVec4(ImGuiCol_Border);
18687
0
        Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), tint_col, border_col);
18688
0
        TreePop();
18689
0
    }
18690
0
}
18691
18692
void ImGui::ShowMetricsWindow(bool* p_open)
18693
0
{
18694
0
    ImGuiContext& g = *GImGui;
18695
0
    ImGuiIO& io = g.IO;
18696
0
    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
18697
0
    if (cfg->ShowDebugLog)
18698
0
        ShowDebugLogWindow(&cfg->ShowDebugLog);
18699
0
    if (cfg->ShowStackTool)
18700
0
        ShowStackToolWindow(&cfg->ShowStackTool);
18701
18702
0
    if (!Begin("Dear ImGui Metrics/Debugger", p_open) || GetCurrentWindow()->BeginCount > 1)
18703
0
    {
18704
0
        End();
18705
0
        return;
18706
0
    }
18707
18708
    // Basic info
18709
0
    Text("Dear ImGui %s", GetVersion());
18710
0
    Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
18711
0
    Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
18712
0
    Text("%d visible windows, %d active allocations", io.MetricsRenderWindows, io.MetricsActiveAllocations);
18713
    //SameLine(); if (SmallButton("GC")) { g.GcCompactAll = true; }
18714
18715
0
    Separator();
18716
18717
    // Debugging enums
18718
0
    enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentIdeal, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type
18719
0
    const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentIdeal", "ContentRegionRect" };
18720
0
    enum { TRT_OuterRect, TRT_InnerRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsWorkRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersIdeal, TRT_ColumnsContentFrozen, TRT_ColumnsContentUnfrozen, TRT_Count }; // Tables Rect Type
18721
0
    const char* trt_rects_names[TRT_Count] = { "OuterRect", "InnerRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsWorkRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen" };
18722
0
    if (cfg->ShowWindowsRectsType < 0)
18723
0
        cfg->ShowWindowsRectsType = WRT_WorkRect;
18724
0
    if (cfg->ShowTablesRectsType < 0)
18725
0
        cfg->ShowTablesRectsType = TRT_WorkRect;
18726
18727
0
    struct Funcs
18728
0
    {
18729
0
        static ImRect GetTableRect(ImGuiTable* table, int rect_type, int n)
18730
0
        {
18731
0
            ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); // Always using last submitted instance
18732
0
            if (rect_type == TRT_OuterRect)                     { return table->OuterRect; }
18733
0
            else if (rect_type == TRT_InnerRect)                { return table->InnerRect; }
18734
0
            else if (rect_type == TRT_WorkRect)                 { return table->WorkRect; }
18735
0
            else if (rect_type == TRT_HostClipRect)             { return table->HostClipRect; }
18736
0
            else if (rect_type == TRT_InnerClipRect)            { return table->InnerClipRect; }
18737
0
            else if (rect_type == TRT_BackgroundClipRect)       { return table->BgClipRect; }
18738
0
            else if (rect_type == TRT_ColumnsRect)              { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MaxX, table->InnerClipRect.Min.y + table_instance->LastOuterHeight); }
18739
0
            else if (rect_type == TRT_ColumnsWorkRect)          { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->WorkRect.Min.y, c->WorkMaxX, table->WorkRect.Max.y); }
18740
0
            else if (rect_type == TRT_ColumnsClipRect)          { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; }
18741
0
            else if (rect_type == TRT_ColumnsContentHeadersUsed){ ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersUsed, table->InnerClipRect.Min.y + table_instance->LastFirstRowHeight); } // Note: y1/y2 not always accurate
18742
0
            else if (rect_type == TRT_ColumnsContentHeadersIdeal){ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersIdeal, table->InnerClipRect.Min.y + table_instance->LastFirstRowHeight); }
18743
0
            else if (rect_type == TRT_ColumnsContentFrozen)     { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXFrozen, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight); }
18744
0
            else if (rect_type == TRT_ColumnsContentUnfrozen)   { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight, c->ContentMaxXUnfrozen, table->InnerClipRect.Max.y); }
18745
0
            IM_ASSERT(0);
18746
0
            return ImRect();
18747
0
        }
18748
18749
0
        static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
18750
0
        {
18751
0
            if (rect_type == WRT_OuterRect)                 { return window->Rect(); }
18752
0
            else if (rect_type == WRT_OuterRectClipped)     { return window->OuterRectClipped; }
18753
0
            else if (rect_type == WRT_InnerRect)            { return window->InnerRect; }
18754
0
            else if (rect_type == WRT_InnerClipRect)        { return window->InnerClipRect; }
18755
0
            else if (rect_type == WRT_WorkRect)             { return window->WorkRect; }
18756
0
            else if (rect_type == WRT_Content)       { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
18757
0
            else if (rect_type == WRT_ContentIdeal)         { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSizeIdeal); }
18758
0
            else if (rect_type == WRT_ContentRegionRect)    { return window->ContentRegionRect; }
18759
0
            IM_ASSERT(0);
18760
0
            return ImRect();
18761
0
        }
18762
0
    };
18763
18764
    // Tools
18765
0
    if (TreeNode("Tools"))
18766
0
    {
18767
0
        bool show_encoding_viewer = TreeNode("UTF-8 Encoding viewer");
18768
0
        SameLine();
18769
0
        MetricsHelpMarker("You can also call ImGui::DebugTextEncoding() from your code with a given string to test that your UTF-8 encoding settings are correct.");
18770
0
        if (show_encoding_viewer)
18771
0
        {
18772
0
            static char buf[100] = "";
18773
0
            SetNextItemWidth(-FLT_MIN);
18774
0
            InputText("##Text", buf, IM_ARRAYSIZE(buf));
18775
0
            if (buf[0] != 0)
18776
0
                DebugTextEncoding(buf);
18777
0
            TreePop();
18778
0
        }
18779
18780
        // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
18781
0
        if (Checkbox("Show Item Picker", &g.DebugItemPickerActive) && g.DebugItemPickerActive)
18782
0
            DebugStartItemPicker();
18783
0
        SameLine();
18784
0
        MetricsHelpMarker("Will call the IM_DEBUG_BREAK() macro to break in debugger.\nWarning: If you don't have a debugger attached, this will probably crash.");
18785
18786
        // Stack Tool is your best friend!
18787
0
        Checkbox("Show Debug Log", &cfg->ShowDebugLog);
18788
0
        SameLine();
18789
0
        MetricsHelpMarker("You can also call ImGui::ShowDebugLogWindow() from your code.");
18790
18791
        // Stack Tool is your best friend!
18792
0
        Checkbox("Show Stack Tool", &cfg->ShowStackTool);
18793
0
        SameLine();
18794
0
        MetricsHelpMarker("You can also call ImGui::ShowStackToolWindow() from your code.");
18795
18796
0
        Checkbox("Show windows begin order", &cfg->ShowWindowsBeginOrder);
18797
0
        Checkbox("Show windows rectangles", &cfg->ShowWindowsRects);
18798
0
        SameLine();
18799
0
        SetNextItemWidth(GetFontSize() * 12);
18800
0
        cfg->ShowWindowsRects |= Combo("##show_windows_rect_type", &cfg->ShowWindowsRectsType, wrt_rects_names, WRT_Count, WRT_Count);
18801
0
        if (cfg->ShowWindowsRects && g.NavWindow != NULL)
18802
0
        {
18803
0
            BulletText("'%s':", g.NavWindow->Name);
18804
0
            Indent();
18805
0
            for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
18806
0
            {
18807
0
                ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n);
18808
0
                Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]);
18809
0
            }
18810
0
            Unindent();
18811
0
        }
18812
18813
0
        Checkbox("Show tables rectangles", &cfg->ShowTablesRects);
18814
0
        SameLine();
18815
0
        SetNextItemWidth(GetFontSize() * 12);
18816
0
        cfg->ShowTablesRects |= Combo("##show_table_rects_type", &cfg->ShowTablesRectsType, trt_rects_names, TRT_Count, TRT_Count);
18817
0
        if (cfg->ShowTablesRects && g.NavWindow != NULL)
18818
0
        {
18819
0
            for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
18820
0
            {
18821
0
                ImGuiTable* table = g.Tables.TryGetMapData(table_n);
18822
0
                if (table == NULL || table->LastFrameActive < g.FrameCount - 1 || (table->OuterWindow != g.NavWindow && table->InnerWindow != g.NavWindow))
18823
0
                    continue;
18824
18825
0
                BulletText("Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name);
18826
0
                if (IsItemHovered())
18827
0
                    GetForegroundDrawList()->AddRect(table->OuterRect.Min - ImVec2(1, 1), table->OuterRect.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
18828
0
                Indent();
18829
0
                char buf[128];
18830
0
                for (int rect_n = 0; rect_n < TRT_Count; rect_n++)
18831
0
                {
18832
0
                    if (rect_n >= TRT_ColumnsRect)
18833
0
                    {
18834
0
                        if (rect_n != TRT_ColumnsRect && rect_n != TRT_ColumnsClipRect)
18835
0
                            continue;
18836
0
                        for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
18837
0
                        {
18838
0
                            ImRect r = Funcs::GetTableRect(table, rect_n, column_n);
18839
0
                            ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) Col %d %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), column_n, trt_rects_names[rect_n]);
18840
0
                            Selectable(buf);
18841
0
                            if (IsItemHovered())
18842
0
                                GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
18843
0
                        }
18844
0
                    }
18845
0
                    else
18846
0
                    {
18847
0
                        ImRect r = Funcs::GetTableRect(table, rect_n, -1);
18848
0
                        ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), trt_rects_names[rect_n]);
18849
0
                        Selectable(buf);
18850
0
                        if (IsItemHovered())
18851
0
                            GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
18852
0
                    }
18853
0
                }
18854
0
                Unindent();
18855
0
            }
18856
0
        }
18857
18858
0
        TreePop();
18859
0
    }
18860
18861
    // Windows
18862
0
    if (TreeNode("Windows", "Windows (%d)", g.Windows.Size))
18863
0
    {
18864
        //SetNextItemOpen(true, ImGuiCond_Once);
18865
0
        DebugNodeWindowsList(&g.Windows, "By display order");
18866
0
        DebugNodeWindowsList(&g.WindowsFocusOrder, "By focus order (root windows)");
18867
0
        if (TreeNode("By submission order (begin stack)"))
18868
0
        {
18869
            // Here we display windows in their submitted order/hierarchy, however note that the Begin stack doesn't constitute a Parent<>Child relationship!
18870
0
            ImVector<ImGuiWindow*>& temp_buffer = g.WindowsTempSortBuffer;
18871
0
            temp_buffer.resize(0);
18872
0
            for (int i = 0; i < g.Windows.Size; i++)
18873
0
                if (g.Windows[i]->LastFrameActive + 1 >= g.FrameCount)
18874
0
                    temp_buffer.push_back(g.Windows[i]);
18875
0
            struct Func { static int IMGUI_CDECL WindowComparerByBeginOrder(const void* lhs, const void* rhs) { return ((int)(*(const ImGuiWindow* const *)lhs)->BeginOrderWithinContext - (*(const ImGuiWindow* const*)rhs)->BeginOrderWithinContext); } };
18876
0
            ImQsort(temp_buffer.Data, (size_t)temp_buffer.Size, sizeof(ImGuiWindow*), Func::WindowComparerByBeginOrder);
18877
0
            DebugNodeWindowsListByBeginStackParent(temp_buffer.Data, temp_buffer.Size, NULL);
18878
0
            TreePop();
18879
0
        }
18880
18881
0
        TreePop();
18882
0
    }
18883
18884
    // DrawLists
18885
0
    int drawlist_count = 0;
18886
0
    for (int viewport_i = 0; viewport_i < g.Viewports.Size; viewport_i++)
18887
0
        drawlist_count += g.Viewports[viewport_i]->DrawDataBuilder.GetDrawListCount();
18888
0
    if (TreeNode("DrawLists", "DrawLists (%d)", drawlist_count))
18889
0
    {
18890
0
        Checkbox("Show ImDrawCmd mesh when hovering", &cfg->ShowDrawCmdMesh);
18891
0
        Checkbox("Show ImDrawCmd bounding boxes when hovering", &cfg->ShowDrawCmdBoundingBoxes);
18892
0
        for (int viewport_i = 0; viewport_i < g.Viewports.Size; viewport_i++)
18893
0
        {
18894
0
            ImGuiViewportP* viewport = g.Viewports[viewport_i];
18895
0
            bool viewport_has_drawlist = false;
18896
0
            for (int layer_i = 0; layer_i < IM_ARRAYSIZE(viewport->DrawDataBuilder.Layers); layer_i++)
18897
0
                for (int draw_list_i = 0; draw_list_i < viewport->DrawDataBuilder.Layers[layer_i].Size; draw_list_i++)
18898
0
                {
18899
0
                    if (!viewport_has_drawlist)
18900
0
                        Text("Active DrawLists in Viewport #%d, ID: 0x%08X", viewport->Idx, viewport->ID);
18901
0
                    viewport_has_drawlist = true;
18902
0
                    DebugNodeDrawList(NULL, viewport, viewport->DrawDataBuilder.Layers[layer_i][draw_list_i], "DrawList");
18903
0
                }
18904
0
        }
18905
0
        TreePop();
18906
0
    }
18907
18908
    // Viewports
18909
0
    if (TreeNode("Viewports", "Viewports (%d)", g.Viewports.Size))
18910
0
    {
18911
0
        Indent(GetTreeNodeToLabelSpacing());
18912
0
        RenderViewportsThumbnails();
18913
0
        Unindent(GetTreeNodeToLabelSpacing());
18914
18915
0
        bool open = TreeNode("Monitors", "Monitors (%d)", g.PlatformIO.Monitors.Size);
18916
0
        SameLine();
18917
0
        MetricsHelpMarker("Dear ImGui uses monitor data:\n- to query DPI settings on a per monitor basis\n- to position popup/tooltips so they don't straddle monitors.");
18918
0
        if (open)
18919
0
        {
18920
0
            for (int i = 0; i < g.PlatformIO.Monitors.Size; i++)
18921
0
            {
18922
0
                const ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[i];
18923
0
                BulletText("Monitor #%d: DPI %.0f%%\n MainMin (%.0f,%.0f), MainMax (%.0f,%.0f), MainSize (%.0f,%.0f)\n WorkMin (%.0f,%.0f), WorkMax (%.0f,%.0f), WorkSize (%.0f,%.0f)",
18924
0
                    i, mon.DpiScale * 100.0f,
18925
0
                    mon.MainPos.x, mon.MainPos.y, mon.MainPos.x + mon.MainSize.x, mon.MainPos.y + mon.MainSize.y, mon.MainSize.x, mon.MainSize.y,
18926
0
                    mon.WorkPos.x, mon.WorkPos.y, mon.WorkPos.x + mon.WorkSize.x, mon.WorkPos.y + mon.WorkSize.y, mon.WorkSize.x, mon.WorkSize.y);
18927
0
            }
18928
0
            TreePop();
18929
0
        }
18930
18931
0
        BulletText("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport ? g.MouseViewport->ID : 0, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
18932
0
        if (TreeNode("Inferred Z order (front-to-back)"))
18933
0
        {
18934
0
            static ImVector<ImGuiViewportP*> viewports;
18935
0
            viewports.resize(g.Viewports.Size);
18936
0
            memcpy(viewports.Data, g.Viewports.Data, g.Viewports.size_in_bytes());
18937
0
            if (viewports.Size > 1)
18938
0
                ImQsort(viewports.Data, viewports.Size, sizeof(ImGuiViewport*), ViewportComparerByFrontMostStampCount);
18939
0
            for (int i = 0; i < viewports.Size; i++)
18940
0
                BulletText("Viewport #%d, ID: 0x%08X, FrontMostStampCount = %08d, Window: \"%s\"", viewports[i]->Idx, viewports[i]->ID, viewports[i]->LastFrontMostStampCount, viewports[i]->Window ? viewports[i]->Window->Name : "N/A");
18941
0
            TreePop();
18942
0
        }
18943
18944
0
        for (int i = 0; i < g.Viewports.Size; i++)
18945
0
            DebugNodeViewport(g.Viewports[i]);
18946
0
        TreePop();
18947
0
    }
18948
18949
    // Details for Popups
18950
0
    if (TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
18951
0
    {
18952
0
        for (int i = 0; i < g.OpenPopupStack.Size; i++)
18953
0
        {
18954
            // As it's difficult to interact with tree nodes while popups are open, we display everything inline.
18955
0
            const ImGuiPopupData* popup_data = &g.OpenPopupStack[i];
18956
0
            ImGuiWindow* window = popup_data->Window;
18957
0
            BulletText("PopupID: %08x, Window: '%s' (%s%s), BackupNavWindow '%s', ParentWindow '%s'",
18958
0
                popup_data->PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? "Child;" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? "Menu;" : "",
18959
0
                popup_data->BackupNavWindow ? popup_data->BackupNavWindow->Name : "NULL", window && window->ParentWindow ? window->ParentWindow->Name : "NULL");
18960
0
        }
18961
0
        TreePop();
18962
0
    }
18963
18964
    // Details for TabBars
18965
0
    if (TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetAliveCount()))
18966
0
    {
18967
0
        for (int n = 0; n < g.TabBars.GetMapSize(); n++)
18968
0
            if (ImGuiTabBar* tab_bar = g.TabBars.TryGetMapData(n))
18969
0
            {
18970
0
                PushID(tab_bar);
18971
0
                DebugNodeTabBar(tab_bar, "TabBar");
18972
0
                PopID();
18973
0
            }
18974
0
        TreePop();
18975
0
    }
18976
18977
    // Details for Tables
18978
0
    if (TreeNode("Tables", "Tables (%d)", g.Tables.GetAliveCount()))
18979
0
    {
18980
0
        for (int n = 0; n < g.Tables.GetMapSize(); n++)
18981
0
            if (ImGuiTable* table = g.Tables.TryGetMapData(n))
18982
0
                DebugNodeTable(table);
18983
0
        TreePop();
18984
0
    }
18985
18986
    // Details for Fonts
18987
0
    ImFontAtlas* atlas = g.IO.Fonts;
18988
0
    if (TreeNode("Fonts", "Fonts (%d)", atlas->Fonts.Size))
18989
0
    {
18990
0
        ShowFontAtlas(atlas);
18991
0
        TreePop();
18992
0
    }
18993
18994
    // Details for InputText
18995
0
    if (TreeNode("InputText"))
18996
0
    {
18997
0
        DebugNodeInputTextState(&g.InputTextState);
18998
0
        TreePop();
18999
0
    }
19000
19001
    // Details for Docking
19002
0
#ifdef IMGUI_HAS_DOCK
19003
0
    if (TreeNode("Docking"))
19004
0
    {
19005
0
        static bool root_nodes_only = true;
19006
0
        ImGuiDockContext* dc = &g.DockContext;
19007
0
        Checkbox("List root nodes", &root_nodes_only);
19008
0
        Checkbox("Ctrl shows window dock info", &cfg->ShowDockingNodes);
19009
0
        if (SmallButton("Clear nodes")) { DockContextClearNodes(&g, 0, true); }
19010
0
        SameLine();
19011
0
        if (SmallButton("Rebuild all")) { dc->WantFullRebuild = true; }
19012
0
        for (int n = 0; n < dc->Nodes.Data.Size; n++)
19013
0
            if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
19014
0
                if (!root_nodes_only || node->IsRootNode())
19015
0
                    DebugNodeDockNode(node, "Node");
19016
0
        TreePop();
19017
0
    }
19018
0
#endif // #ifdef IMGUI_HAS_DOCK
19019
19020
    // Settings
19021
0
    if (TreeNode("Settings"))
19022
0
    {
19023
0
        if (SmallButton("Clear"))
19024
0
            ClearIniSettings();
19025
0
        SameLine();
19026
0
        if (SmallButton("Save to memory"))
19027
0
            SaveIniSettingsToMemory();
19028
0
        SameLine();
19029
0
        if (SmallButton("Save to disk"))
19030
0
            SaveIniSettingsToDisk(g.IO.IniFilename);
19031
0
        SameLine();
19032
0
        if (g.IO.IniFilename)
19033
0
            Text("\"%s\"", g.IO.IniFilename);
19034
0
        else
19035
0
            TextUnformatted("<NULL>");
19036
0
        Text("SettingsDirtyTimer %.2f", g.SettingsDirtyTimer);
19037
0
        if (TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size))
19038
0
        {
19039
0
            for (int n = 0; n < g.SettingsHandlers.Size; n++)
19040
0
                BulletText("%s", g.SettingsHandlers[n].TypeName);
19041
0
            TreePop();
19042
0
        }
19043
0
        if (TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size()))
19044
0
        {
19045
0
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19046
0
                DebugNodeWindowSettings(settings);
19047
0
            TreePop();
19048
0
        }
19049
19050
0
        if (TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size()))
19051
0
        {
19052
0
            for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
19053
0
                DebugNodeTableSettings(settings);
19054
0
            TreePop();
19055
0
        }
19056
19057
0
#ifdef IMGUI_HAS_DOCK
19058
0
        if (TreeNode("SettingsDocking", "Settings packed data: Docking"))
19059
0
        {
19060
0
            ImGuiDockContext* dc = &g.DockContext;
19061
0
            Text("In SettingsWindows:");
19062
0
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19063
0
                if (settings->DockId != 0)
19064
0
                    BulletText("Window '%s' -> DockId %08X", settings->GetName(), settings->DockId);
19065
0
            Text("In SettingsNodes:");
19066
0
            for (int n = 0; n < dc->NodesSettings.Size; n++)
19067
0
            {
19068
0
                ImGuiDockNodeSettings* settings = &dc->NodesSettings[n];
19069
0
                const char* selected_tab_name = NULL;
19070
0
                if (settings->SelectedTabId)
19071
0
                {
19072
0
                    if (ImGuiWindow* window = FindWindowByID(settings->SelectedTabId))
19073
0
                        selected_tab_name = window->Name;
19074
0
                    else if (ImGuiWindowSettings* window_settings = FindWindowSettings(settings->SelectedTabId))
19075
0
                        selected_tab_name = window_settings->GetName();
19076
0
                }
19077
0
                BulletText("Node %08X, Parent %08X, SelectedTab %08X ('%s')", settings->ID, settings->ParentNodeId, settings->SelectedTabId, selected_tab_name ? selected_tab_name : settings->SelectedTabId ? "N/A" : "");
19078
0
            }
19079
0
            TreePop();
19080
0
        }
19081
0
#endif // #ifdef IMGUI_HAS_DOCK
19082
19083
0
        if (TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size()))
19084
0
        {
19085
0
            InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly);
19086
0
            TreePop();
19087
0
        }
19088
0
        TreePop();
19089
0
    }
19090
19091
0
    if (TreeNode("Inputs"))
19092
0
    {
19093
0
        Text("KEYBOARD/GAMEPAD/MOUSE KEYS");
19094
0
        {
19095
            // We iterate both legacy native range and named ImGuiKey ranges, which is a little odd but this allows displaying the data for old/new backends.
19096
            // User code should never have to go through such hoops: old code may use native keycodes, new code may use ImGuiKey codes.
19097
0
            Indent();
19098
0
#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
19099
0
            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey) { return false; } };
19100
#else
19101
            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey key) { return key < 512 && GetIO().KeyMap[key] != -1; } }; // Hide Native<>ImGuiKey duplicates when both exists in the array
19102
            //Text("Legacy raw:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key++) { if (io.KeysDown[key]) { SameLine(); Text("\"%s\" %d", GetKeyName(key), key); } }
19103
#endif
19104
0
            Text("Keys down:");         for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyDown(key)) continue;     SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); SameLine(); Text("(%.02f)", GetKeyData(key)->DownDuration); }
19105
0
            Text("Keys pressed:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyPressed(key)) continue;  SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
19106
0
            Text("Keys released:");     for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyReleased(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
19107
0
            Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : "");
19108
0
            Text("Chars queue:");       for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; SameLine(); Text("\'%c\' (0x%04X)", (c > ' ' && c <= 255) ? (char)c : '?', c); } // FIXME: We should convert 'c' to UTF-8 here but the functions are not public.
19109
0
            DebugRenderKeyboardPreview(GetWindowDrawList());
19110
0
            Unindent();
19111
0
        }
19112
19113
0
        Text("MOUSE STATE");
19114
0
        {
19115
0
            Indent();
19116
0
            if (IsMousePosValid())
19117
0
                Text("Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y);
19118
0
            else
19119
0
                Text("Mouse pos: <INVALID>");
19120
0
            Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y);
19121
0
            int count = IM_ARRAYSIZE(io.MouseDown);
19122
0
            Text("Mouse down:");     for (int i = 0; i < count; i++) if (IsMouseDown(i)) { SameLine(); Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); }
19123
0
            Text("Mouse clicked:");  for (int i = 0; i < count; i++) if (IsMouseClicked(i)) { SameLine(); Text("b%d (%d)", i, io.MouseClickedCount[i]); }
19124
0
            Text("Mouse released:"); for (int i = 0; i < count; i++) if (IsMouseReleased(i)) { SameLine(); Text("b%d", i); }
19125
0
            Text("Mouse wheel: %.1f", io.MouseWheel);
19126
0
            Text("Pen Pressure: %.1f", io.PenPressure); // Note: currently unused
19127
0
            Unindent();
19128
0
        }
19129
19130
0
        Text("MOUSE WHEELING");
19131
0
        {
19132
0
            Indent();
19133
0
            Text("WheelingWindow: '%s'", g.WheelingWindow ? g.WheelingWindow->Name : "NULL");
19134
0
            Text("WheelingWindowReleaseTimer: %.2f", g.WheelingWindowReleaseTimer);
19135
0
            Text("WheelingAxisAvg[] = { %.3f, %.3f }, Main Axis: %s", g.WheelingAxisAvg.x, g.WheelingAxisAvg.y, (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? "X" : (g.WheelingAxisAvg.x < g.WheelingAxisAvg.y) ? "Y" : "<none>");
19136
0
            Unindent();
19137
0
        }
19138
19139
0
        Text("KEY OWNERS");
19140
0
        {
19141
0
            Indent();
19142
0
            if (BeginListBox("##owners", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 6)))
19143
0
            {
19144
0
                for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
19145
0
                {
19146
0
                    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(key);
19147
0
                    if (owner_data->OwnerCurr == ImGuiKeyOwner_None)
19148
0
                        continue;
19149
0
                    Text("%s: 0x%08X%s", GetKeyName(key), owner_data->OwnerCurr,
19150
0
                        owner_data->LockUntilRelease ? " LockUntilRelease" : owner_data->LockThisFrame ? " LockThisFrame" : "");
19151
0
                    DebugLocateItemOnHover(owner_data->OwnerCurr);
19152
0
                }
19153
0
                EndListBox();
19154
0
            }
19155
0
            Unindent();
19156
0
        }
19157
0
        Text("SHORTCUT ROUTING");
19158
0
        {
19159
0
            Indent();
19160
0
            if (BeginListBox("##routes", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 6)))
19161
0
            {
19162
0
                for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
19163
0
                {
19164
0
                    ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
19165
0
                    for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; )
19166
0
                    {
19167
0
                        char key_chord_name[64];
19168
0
                        ImGuiKeyRoutingData* routing_data = &rt->Entries[idx];
19169
0
                        GetKeyChordName(key | routing_data->Mods, key_chord_name, IM_ARRAYSIZE(key_chord_name));
19170
0
                        Text("%s: 0x%08X", key_chord_name, routing_data->RoutingCurr);
19171
0
                        DebugLocateItemOnHover(routing_data->RoutingCurr);
19172
0
                        idx = routing_data->NextEntryIndex;
19173
0
                    }
19174
0
                }
19175
0
                EndListBox();
19176
0
            }
19177
0
            Text("(ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: 0x%X)", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
19178
0
            Unindent();
19179
0
        }
19180
0
        TreePop();
19181
0
    }
19182
19183
0
    if (TreeNode("Internal state"))
19184
0
    {
19185
0
        Text("WINDOWING");
19186
0
        Indent();
19187
0
        Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
19188
0
        Text("HoveredWindow->Root: '%s'", g.HoveredWindow ? g.HoveredWindow->RootWindowDockTree->Name : "NULL");
19189
0
        Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL");
19190
0
        Text("HoveredDockNode: 0x%08X", g.DebugHoveredDockNode ? g.DebugHoveredDockNode->ID : 0);
19191
0
        Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
19192
0
        Text("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport->ID, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
19193
0
        Unindent();
19194
19195
0
        Text("ITEMS");
19196
0
        Indent();
19197
0
        Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, GetInputSourceName(g.ActiveIdSource));
19198
0
        DebugLocateItemOnHover(g.ActiveId);
19199
0
        Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
19200
0
        Text("ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: %X", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
19201
0
        Text("HoveredId: 0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Not displaying g.HoveredId as it is update mid-frame
19202
0
        Text("HoverDelayId: 0x%08X, Timer: %.2f, ClearTimer: %.2f", g.HoverDelayId, g.HoverDelayTimer, g.HoverDelayClearTimer);
19203
0
        Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
19204
0
        DebugLocateItemOnHover(g.DragDropPayload.SourceId);
19205
0
        Unindent();
19206
19207
0
        Text("NAV,FOCUS");
19208
0
        Indent();
19209
0
        Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
19210
0
        Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
19211
0
        DebugLocateItemOnHover(g.NavId);
19212
0
        Text("NavInputSource: %s", GetInputSourceName(g.NavInputSource));
19213
0
        Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
19214
0
        Text("NavActivateId/DownId/PressedId/InputId: %08X/%08X/%08X/%08X", g.NavActivateId, g.NavActivateDownId, g.NavActivatePressedId, g.NavActivateInputId);
19215
0
        Text("NavActivateFlags: %04X", g.NavActivateFlags);
19216
0
        Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
19217
0
        Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId);
19218
0
        Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
19219
0
        Unindent();
19220
19221
0
        TreePop();
19222
0
    }
19223
19224
    // Overlay: Display windows Rectangles and Begin Order
19225
0
    if (cfg->ShowWindowsRects || cfg->ShowWindowsBeginOrder)
19226
0
    {
19227
0
        for (int n = 0; n < g.Windows.Size; n++)
19228
0
        {
19229
0
            ImGuiWindow* window = g.Windows[n];
19230
0
            if (!window->WasActive)
19231
0
                continue;
19232
0
            ImDrawList* draw_list = GetForegroundDrawList(window);
19233
0
            if (cfg->ShowWindowsRects)
19234
0
            {
19235
0
                ImRect r = Funcs::GetWindowRect(window, cfg->ShowWindowsRectsType);
19236
0
                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
19237
0
            }
19238
0
            if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow))
19239
0
            {
19240
0
                char buf[32];
19241
0
                ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
19242
0
                float font_size = GetFontSize();
19243
0
                draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
19244
0
                draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf);
19245
0
            }
19246
0
        }
19247
0
    }
19248
19249
    // Overlay: Display Tables Rectangles
19250
0
    if (cfg->ShowTablesRects)
19251
0
    {
19252
0
        for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
19253
0
        {
19254
0
            ImGuiTable* table = g.Tables.TryGetMapData(table_n);
19255
0
            if (table == NULL || table->LastFrameActive < g.FrameCount - 1)
19256
0
                continue;
19257
0
            ImDrawList* draw_list = GetForegroundDrawList(table->OuterWindow);
19258
0
            if (cfg->ShowTablesRectsType >= TRT_ColumnsRect)
19259
0
            {
19260
0
                for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
19261
0
                {
19262
0
                    ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, column_n);
19263
0
                    ImU32 col = (table->HoveredColumnBody == column_n) ? IM_COL32(255, 255, 128, 255) : IM_COL32(255, 0, 128, 255);
19264
0
                    float thickness = (table->HoveredColumnBody == column_n) ? 3.0f : 1.0f;
19265
0
                    draw_list->AddRect(r.Min, r.Max, col, 0.0f, 0, thickness);
19266
0
                }
19267
0
            }
19268
0
            else
19269
0
            {
19270
0
                ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, -1);
19271
0
                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
19272
0
            }
19273
0
        }
19274
0
    }
19275
19276
0
#ifdef IMGUI_HAS_DOCK
19277
    // Overlay: Display Docking info
19278
0
    if (cfg->ShowDockingNodes && g.IO.KeyCtrl && g.DebugHoveredDockNode)
19279
0
    {
19280
0
        char buf[64] = "";
19281
0
        char* p = buf;
19282
0
        ImGuiDockNode* node = g.DebugHoveredDockNode;
19283
0
        ImDrawList* overlay_draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
19284
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "DockId: %X%s\n", node->ID, node->IsCentralNode() ? " *CentralNode*" : "");
19285
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "WindowClass: %08X\n", node->WindowClass.ClassId);
19286
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "Size: (%.0f, %.0f)\n", node->Size.x, node->Size.y);
19287
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "SizeRef: (%.0f, %.0f)\n", node->SizeRef.x, node->SizeRef.y);
19288
0
        int depth = DockNodeGetDepth(node);
19289
0
        overlay_draw_list->AddRect(node->Pos + ImVec2(3, 3) * (float)depth, node->Pos + node->Size - ImVec2(3, 3) * (float)depth, IM_COL32(200, 100, 100, 255));
19290
0
        ImVec2 pos = node->Pos + ImVec2(3, 3) * (float)depth;
19291
0
        overlay_draw_list->AddRectFilled(pos - ImVec2(1, 1), pos + CalcTextSize(buf) + ImVec2(1, 1), IM_COL32(200, 100, 100, 255));
19292
0
        overlay_draw_list->AddText(NULL, 0.0f, pos, IM_COL32(255, 255, 255, 255), buf);
19293
0
    }
19294
0
#endif // #ifdef IMGUI_HAS_DOCK
19295
19296
0
    End();
19297
0
}
19298
19299
// [DEBUG] Display contents of Columns
19300
void ImGui::DebugNodeColumns(ImGuiOldColumns* columns)
19301
0
{
19302
0
    if (!TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
19303
0
        return;
19304
0
    BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
19305
0
    for (int column_n = 0; column_n < columns->Columns.Size; column_n++)
19306
0
        BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", column_n, columns->Columns[column_n].OffsetNorm, GetColumnOffsetFromNorm(columns, columns->Columns[column_n].OffsetNorm));
19307
0
    TreePop();
19308
0
}
19309
19310
static void DebugNodeDockNodeFlags(ImGuiDockNodeFlags* p_flags, const char* label, bool enabled)
19311
0
{
19312
0
    using namespace ImGui;
19313
0
    PushID(label);
19314
0
    PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.0f));
19315
0
    Text("%s:", label);
19316
0
    if (!enabled)
19317
0
        BeginDisabled();
19318
0
    CheckboxFlags("NoSplit", p_flags, ImGuiDockNodeFlags_NoSplit);
19319
0
    CheckboxFlags("NoResize", p_flags, ImGuiDockNodeFlags_NoResize);
19320
0
    CheckboxFlags("NoResizeX", p_flags, ImGuiDockNodeFlags_NoResizeX);
19321
0
    CheckboxFlags("NoResizeY",p_flags, ImGuiDockNodeFlags_NoResizeY);
19322
0
    CheckboxFlags("NoTabBar", p_flags, ImGuiDockNodeFlags_NoTabBar);
19323
0
    CheckboxFlags("HiddenTabBar", p_flags, ImGuiDockNodeFlags_HiddenTabBar);
19324
0
    CheckboxFlags("NoWindowMenuButton", p_flags, ImGuiDockNodeFlags_NoWindowMenuButton);
19325
0
    CheckboxFlags("NoCloseButton", p_flags, ImGuiDockNodeFlags_NoCloseButton);
19326
0
    CheckboxFlags("NoDocking", p_flags, ImGuiDockNodeFlags_NoDocking);
19327
0
    CheckboxFlags("NoDockingSplitMe", p_flags, ImGuiDockNodeFlags_NoDockingSplitMe);
19328
0
    CheckboxFlags("NoDockingSplitOther", p_flags, ImGuiDockNodeFlags_NoDockingSplitOther);
19329
0
    CheckboxFlags("NoDockingOverMe", p_flags, ImGuiDockNodeFlags_NoDockingOverMe);
19330
0
    CheckboxFlags("NoDockingOverOther", p_flags, ImGuiDockNodeFlags_NoDockingOverOther);
19331
0
    CheckboxFlags("NoDockingOverEmpty", p_flags, ImGuiDockNodeFlags_NoDockingOverEmpty);
19332
0
    if (!enabled)
19333
0
        EndDisabled();
19334
0
    PopStyleVar();
19335
0
    PopID();
19336
0
}
19337
19338
// [DEBUG] Display contents of ImDockNode
19339
void ImGui::DebugNodeDockNode(ImGuiDockNode* node, const char* label)
19340
0
{
19341
0
    ImGuiContext& g = *GImGui;
19342
0
    const bool is_alive = (g.FrameCount - node->LastFrameAlive < 2);    // Submitted with ImGuiDockNodeFlags_KeepAliveOnly
19343
0
    const bool is_active = (g.FrameCount - node->LastFrameActive < 2);  // Submitted
19344
0
    if (!is_alive) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
19345
0
    bool open;
19346
0
    ImGuiTreeNodeFlags tree_node_flags = node->IsFocused ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
19347
0
    if (node->Windows.Size > 0)
19348
0
        open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %d windows (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", node->Windows.Size, node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
19349
0
    else
19350
0
        open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %s (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", (node->SplitAxis == ImGuiAxis_X) ? "horizontal split" : (node->SplitAxis == ImGuiAxis_Y) ? "vertical split" : "empty", node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
19351
0
    if (!is_alive) { PopStyleColor(); }
19352
0
    if (is_active && IsItemHovered())
19353
0
        if (ImGuiWindow* window = node->HostWindow ? node->HostWindow : node->VisibleWindow)
19354
0
            GetForegroundDrawList(window)->AddRect(node->Pos, node->Pos + node->Size, IM_COL32(255, 255, 0, 255));
19355
0
    if (open)
19356
0
    {
19357
0
        IM_ASSERT(node->ChildNodes[0] == NULL || node->ChildNodes[0]->ParentNode == node);
19358
0
        IM_ASSERT(node->ChildNodes[1] == NULL || node->ChildNodes[1]->ParentNode == node);
19359
0
        BulletText("Pos (%.0f,%.0f), Size (%.0f, %.0f) Ref (%.0f, %.0f)",
19360
0
            node->Pos.x, node->Pos.y, node->Size.x, node->Size.y, node->SizeRef.x, node->SizeRef.y);
19361
0
        DebugNodeWindow(node->HostWindow, "HostWindow");
19362
0
        DebugNodeWindow(node->VisibleWindow, "VisibleWindow");
19363
0
        BulletText("SelectedTabID: 0x%08X, LastFocusedNodeID: 0x%08X", node->SelectedTabId, node->LastFocusedNodeId);
19364
0
        BulletText("Misc:%s%s%s%s%s%s%s",
19365
0
            node->IsDockSpace() ? " IsDockSpace" : "",
19366
0
            node->IsCentralNode() ? " IsCentralNode" : "",
19367
0
            is_alive ? " IsAlive" : "", is_active ? " IsActive" : "", node->IsFocused ? " IsFocused" : "",
19368
0
            node->WantLockSizeOnce ? " WantLockSizeOnce" : "",
19369
0
            node->HasCentralNodeChild ? " HasCentralNodeChild" : "");
19370
0
        if (TreeNode("flags", "Flags Merged: 0x%04X, Local: 0x%04X, InWindows: 0x%04X, Shared: 0x%04X", node->MergedFlags, node->LocalFlags, node->LocalFlagsInWindows, node->SharedFlags))
19371
0
        {
19372
0
            if (BeginTable("flags", 4))
19373
0
            {
19374
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->MergedFlags, "MergedFlags", false);
19375
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlags, "LocalFlags", true);
19376
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlagsInWindows, "LocalFlagsInWindows", false);
19377
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->SharedFlags, "SharedFlags", true);
19378
0
                EndTable();
19379
0
            }
19380
0
            TreePop();
19381
0
        }
19382
0
        if (node->ParentNode)
19383
0
            DebugNodeDockNode(node->ParentNode, "ParentNode");
19384
0
        if (node->ChildNodes[0])
19385
0
            DebugNodeDockNode(node->ChildNodes[0], "Child[0]");
19386
0
        if (node->ChildNodes[1])
19387
0
            DebugNodeDockNode(node->ChildNodes[1], "Child[1]");
19388
0
        if (node->TabBar)
19389
0
            DebugNodeTabBar(node->TabBar, "TabBar");
19390
0
        DebugNodeWindowsList(&node->Windows, "Windows");
19391
19392
0
        TreePop();
19393
0
    }
19394
0
}
19395
19396
// [DEBUG] Display contents of ImDrawList
19397
// Note that both 'window' and 'viewport' may be NULL here. Viewport is generally null of destroyed popups which previously owned a viewport.
19398
void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label)
19399
0
{
19400
0
    ImGuiContext& g = *GImGui;
19401
0
    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
19402
0
    int cmd_count = draw_list->CmdBuffer.Size;
19403
0
    if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL)
19404
0
        cmd_count--;
19405
0
    bool node_open = TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, cmd_count);
19406
0
    if (draw_list == GetWindowDrawList())
19407
0
    {
19408
0
        SameLine();
19409
0
        TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
19410
0
        if (node_open)
19411
0
            TreePop();
19412
0
        return;
19413
0
    }
19414
19415
0
    ImDrawList* fg_draw_list = viewport ? GetForegroundDrawList(viewport) : NULL; // Render additional visuals into the top-most draw list
19416
0
    if (window && IsItemHovered() && fg_draw_list)
19417
0
        fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
19418
0
    if (!node_open)
19419
0
        return;
19420
19421
0
    if (window && !window->WasActive)
19422
0
        TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!");
19423
19424
0
    for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++)
19425
0
    {
19426
0
        if (pcmd->UserCallback)
19427
0
        {
19428
0
            BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
19429
0
            continue;
19430
0
        }
19431
19432
0
        char buf[300];
19433
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex 0x%p, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
19434
0
            pcmd->ElemCount / 3, (void*)(intptr_t)pcmd->TextureId,
19435
0
            pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
19436
0
        bool pcmd_node_open = TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf);
19437
0
        if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list)
19438
0
            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, cfg->ShowDrawCmdMesh, cfg->ShowDrawCmdBoundingBoxes);
19439
0
        if (!pcmd_node_open)
19440
0
            continue;
19441
19442
        // Calculate approximate coverage area (touched pixel count)
19443
        // This will be in pixels squared as long there's no post-scaling happening to the renderer output.
19444
0
        const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
19445
0
        const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset;
19446
0
        float total_area = 0.0f;
19447
0
        for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; )
19448
0
        {
19449
0
            ImVec2 triangle[3];
19450
0
            for (int n = 0; n < 3; n++, idx_n++)
19451
0
                triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos;
19452
0
            total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]);
19453
0
        }
19454
19455
        // Display vertex information summary. Hover to get all triangles drawn in wire-frame
19456
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area);
19457
0
        Selectable(buf);
19458
0
        if (IsItemHovered() && fg_draw_list)
19459
0
            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, true, false);
19460
19461
        // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
19462
0
        ImGuiListClipper clipper;
19463
0
        clipper.Begin(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
19464
0
        while (clipper.Step())
19465
0
            for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++)
19466
0
            {
19467
0
                char* buf_p = buf, * buf_end = buf + IM_ARRAYSIZE(buf);
19468
0
                ImVec2 triangle[3];
19469
0
                for (int n = 0; n < 3; n++, idx_i++)
19470
0
                {
19471
0
                    const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i];
19472
0
                    triangle[n] = v.pos;
19473
0
                    buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
19474
0
                        (n == 0) ? "Vert:" : "     ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
19475
0
                }
19476
19477
0
                Selectable(buf, false);
19478
0
                if (fg_draw_list && IsItemHovered())
19479
0
                {
19480
0
                    ImDrawListFlags backup_flags = fg_draw_list->Flags;
19481
0
                    fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
19482
0
                    fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f);
19483
0
                    fg_draw_list->Flags = backup_flags;
19484
0
                }
19485
0
            }
19486
0
        TreePop();
19487
0
    }
19488
0
    TreePop();
19489
0
}
19490
19491
// [DEBUG] Display mesh/aabb of a ImDrawCmd
19492
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb)
19493
0
{
19494
0
    IM_ASSERT(show_mesh || show_aabb);
19495
19496
    // Draw wire-frame version of all triangles
19497
0
    ImRect clip_rect = draw_cmd->ClipRect;
19498
0
    ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
19499
0
    ImDrawListFlags backup_flags = out_draw_list->Flags;
19500
0
    out_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
19501
0
    for (unsigned int idx_n = draw_cmd->IdxOffset, idx_end = draw_cmd->IdxOffset + draw_cmd->ElemCount; idx_n < idx_end; )
19502
0
    {
19503
0
        ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; // We don't hold on those pointers past iterations as ->AddPolyline() may invalidate them if out_draw_list==draw_list
19504
0
        ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset;
19505
19506
0
        ImVec2 triangle[3];
19507
0
        for (int n = 0; n < 3; n++, idx_n++)
19508
0
            vtxs_rect.Add((triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos));
19509
0
        if (show_mesh)
19510
0
            out_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f); // In yellow: mesh triangles
19511
0
    }
19512
    // Draw bounding boxes
19513
0
    if (show_aabb)
19514
0
    {
19515
0
        out_draw_list->AddRect(ImFloor(clip_rect.Min), ImFloor(clip_rect.Max), IM_COL32(255, 0, 255, 255)); // In pink: clipping rectangle submitted to GPU
19516
0
        out_draw_list->AddRect(ImFloor(vtxs_rect.Min), ImFloor(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles
19517
0
    }
19518
0
    out_draw_list->Flags = backup_flags;
19519
0
}
19520
19521
// [DEBUG] Display details for a single font, called by ShowStyleEditor().
19522
void ImGui::DebugNodeFont(ImFont* font)
19523
0
{
19524
0
    bool opened = TreeNode(font, "Font: \"%s\"\n%.2f px, %d glyphs, %d file(s)",
19525
0
        font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount);
19526
0
    SameLine();
19527
0
    if (SmallButton("Set as default"))
19528
0
        GetIO().FontDefault = font;
19529
0
    if (!opened)
19530
0
        return;
19531
19532
    // Display preview text
19533
0
    PushFont(font);
19534
0
    Text("The quick brown fox jumps over the lazy dog");
19535
0
    PopFont();
19536
19537
    // Display details
19538
0
    SetNextItemWidth(GetFontSize() * 8);
19539
0
    DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f");
19540
0
    SameLine(); MetricsHelpMarker(
19541
0
        "Note than the default embedded font is NOT meant to be scaled.\n\n"
19542
0
        "Font are currently rendered into bitmaps at a given size at the time of building the atlas. "
19543
0
        "You may oversample them to get some flexibility with scaling. "
19544
0
        "You can also render at multiple sizes and select which one to use at runtime.\n\n"
19545
0
        "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)");
19546
0
    Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent);
19547
0
    char c_str[5];
19548
0
    Text("Fallback character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->FallbackChar), font->FallbackChar);
19549
0
    Text("Ellipsis character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->EllipsisChar), font->EllipsisChar);
19550
0
    const int surface_sqrt = (int)ImSqrt((float)font->MetricsTotalSurface);
19551
0
    Text("Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, surface_sqrt, surface_sqrt);
19552
0
    for (int config_i = 0; config_i < font->ConfigDataCount; config_i++)
19553
0
        if (font->ConfigData)
19554
0
            if (const ImFontConfig* cfg = &font->ConfigData[config_i])
19555
0
                BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d, Offset: (%.1f,%.1f)",
19556
0
                    config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH, cfg->GlyphOffset.x, cfg->GlyphOffset.y);
19557
19558
    // Display all glyphs of the fonts in separate pages of 256 characters
19559
0
    if (TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size))
19560
0
    {
19561
0
        ImDrawList* draw_list = GetWindowDrawList();
19562
0
        const ImU32 glyph_col = GetColorU32(ImGuiCol_Text);
19563
0
        const float cell_size = font->FontSize * 1;
19564
0
        const float cell_spacing = GetStyle().ItemSpacing.y;
19565
0
        for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256)
19566
0
        {
19567
            // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k)
19568
            // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT
19569
            // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here)
19570
0
            if (!(base & 4095) && font->IsGlyphRangeUnused(base, base + 4095))
19571
0
            {
19572
0
                base += 4096 - 256;
19573
0
                continue;
19574
0
            }
19575
19576
0
            int count = 0;
19577
0
            for (unsigned int n = 0; n < 256; n++)
19578
0
                if (font->FindGlyphNoFallback((ImWchar)(base + n)))
19579
0
                    count++;
19580
0
            if (count <= 0)
19581
0
                continue;
19582
0
            if (!TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph"))
19583
0
                continue;
19584
19585
            // Draw a 16x16 grid of glyphs
19586
0
            ImVec2 base_pos = GetCursorScreenPos();
19587
0
            for (unsigned int n = 0; n < 256; n++)
19588
0
            {
19589
                // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions
19590
                // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string.
19591
0
                ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing));
19592
0
                ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size);
19593
0
                const ImFontGlyph* glyph = font->FindGlyphNoFallback((ImWchar)(base + n));
19594
0
                draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50));
19595
0
                if (!glyph)
19596
0
                    continue;
19597
0
                font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n));
19598
0
                if (IsMouseHoveringRect(cell_p1, cell_p2))
19599
0
                {
19600
0
                    BeginTooltip();
19601
0
                    DebugNodeFontGlyph(font, glyph);
19602
0
                    EndTooltip();
19603
0
                }
19604
0
            }
19605
0
            Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));
19606
0
            TreePop();
19607
0
        }
19608
0
        TreePop();
19609
0
    }
19610
0
    TreePop();
19611
0
}
19612
19613
void ImGui::DebugNodeFontGlyph(ImFont*, const ImFontGlyph* glyph)
19614
0
{
19615
0
    Text("Codepoint: U+%04X", glyph->Codepoint);
19616
0
    Separator();
19617
0
    Text("Visible: %d", glyph->Visible);
19618
0
    Text("AdvanceX: %.1f", glyph->AdvanceX);
19619
0
    Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1);
19620
0
    Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1);
19621
0
}
19622
19623
// [DEBUG] Display contents of ImGuiStorage
19624
void ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label)
19625
0
{
19626
0
    if (!TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes()))
19627
0
        return;
19628
0
    for (int n = 0; n < storage->Data.Size; n++)
19629
0
    {
19630
0
        const ImGuiStorage::ImGuiStoragePair& p = storage->Data[n];
19631
0
        BulletText("Key 0x%08X Value { i: %d }", p.key, p.val_i); // Important: we currently don't store a type, real value may not be integer.
19632
0
    }
19633
0
    TreePop();
19634
0
}
19635
19636
// [DEBUG] Display contents of ImGuiTabBar
19637
void ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label)
19638
0
{
19639
    // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
19640
0
    char buf[256];
19641
0
    char* p = buf;
19642
0
    const char* buf_end = buf + IM_ARRAYSIZE(buf);
19643
0
    const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2);
19644
0
    p += ImFormatString(p, buf_end - p, "%s 0x%08X (%d tabs)%s", label, tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*");
19645
0
    p += ImFormatString(p, buf_end - p, "  { ");
19646
0
    for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++)
19647
0
    {
19648
0
        ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
19649
0
        p += ImFormatString(p, buf_end - p, "%s'%s'",
19650
0
            tab_n > 0 ? ", " : "", (tab->Window || tab->NameOffset != -1) ? TabBarGetTabName(tab_bar, tab) : "???");
19651
0
    }
19652
0
    p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } ");
19653
0
    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
19654
0
    bool open = TreeNode(label, "%s", buf);
19655
0
    if (!is_active) { PopStyleColor(); }
19656
0
    if (is_active && IsItemHovered())
19657
0
    {
19658
0
        ImDrawList* draw_list = GetForegroundDrawList();
19659
0
        draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255));
19660
0
        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
19661
0
        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
19662
0
    }
19663
0
    if (open)
19664
0
    {
19665
0
        for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
19666
0
        {
19667
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
19668
0
            PushID(tab);
19669
0
            if (SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } SameLine(0, 2);
19670
0
            if (SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } SameLine();
19671
0
            Text("%02d%c Tab 0x%08X '%s' Offset: %.2f, Width: %.2f/%.2f",
19672
0
                tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, (tab->Window || tab->NameOffset != -1) ? TabBarGetTabName(tab_bar, tab) : "???", tab->Offset, tab->Width, tab->ContentWidth);
19673
0
            PopID();
19674
0
        }
19675
0
        TreePop();
19676
0
    }
19677
0
}
19678
19679
void ImGui::DebugNodeViewport(ImGuiViewportP* viewport)
19680
0
{
19681
0
    SetNextItemOpen(true, ImGuiCond_Once);
19682
0
    if (TreeNode((void*)(intptr_t)viewport->ID, "Viewport #%d, ID: 0x%08X, Parent: 0x%08X, Window: \"%s\"", viewport->Idx, viewport->ID, viewport->ParentViewportId, viewport->Window ? viewport->Window->Name : "N/A"))
19683
0
    {
19684
0
        ImGuiWindowFlags flags = viewport->Flags;
19685
0
        BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nWorkArea Offset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f\nMonitor: %d, DpiScale: %.0f%%",
19686
0
            viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y,
19687
0
            viewport->WorkOffsetMin.x, viewport->WorkOffsetMin.y, viewport->WorkOffsetMax.x, viewport->WorkOffsetMax.y,
19688
0
            viewport->PlatformMonitor, viewport->DpiScale * 100.0f);
19689
0
        if (viewport->Idx > 0) { SameLine(); if (SmallButton("Reset Pos")) { viewport->Pos = ImVec2(200, 200); viewport->UpdateWorkRect(); if (viewport->Window) viewport->Window->Pos = viewport->Pos; } }
19690
0
        BulletText("Flags: 0x%04X =%s%s%s%s%s%s%s%s%s%s%s%s", viewport->Flags,
19691
            //(flags & ImGuiViewportFlags_IsPlatformWindow) ? " IsPlatformWindow" : "", // Omitting because it is the standard
19692
0
            (flags & ImGuiViewportFlags_IsPlatformMonitor) ? " IsPlatformMonitor" : "",
19693
0
            (flags & ImGuiViewportFlags_OwnedByApp) ? " OwnedByApp" : "",
19694
0
            (flags & ImGuiViewportFlags_NoDecoration) ? " NoDecoration" : "",
19695
0
            (flags & ImGuiViewportFlags_NoTaskBarIcon) ? " NoTaskBarIcon" : "",
19696
0
            (flags & ImGuiViewportFlags_NoFocusOnAppearing) ? " NoFocusOnAppearing" : "",
19697
0
            (flags & ImGuiViewportFlags_NoFocusOnClick) ? " NoFocusOnClick" : "",
19698
0
            (flags & ImGuiViewportFlags_NoInputs) ? " NoInputs" : "",
19699
0
            (flags & ImGuiViewportFlags_NoRendererClear) ? " NoRendererClear" : "",
19700
0
            (flags & ImGuiViewportFlags_TopMost) ? " TopMost" : "",
19701
0
            (flags & ImGuiViewportFlags_Minimized) ? " Minimized" : "",
19702
0
            (flags & ImGuiViewportFlags_NoAutoMerge) ? " NoAutoMerge" : "",
19703
0
            (flags & ImGuiViewportFlags_CanHostOtherWindows) ? " CanHostOtherWindows" : "");
19704
0
        for (int layer_i = 0; layer_i < IM_ARRAYSIZE(viewport->DrawDataBuilder.Layers); layer_i++)
19705
0
            for (int draw_list_i = 0; draw_list_i < viewport->DrawDataBuilder.Layers[layer_i].Size; draw_list_i++)
19706
0
                DebugNodeDrawList(NULL, viewport, viewport->DrawDataBuilder.Layers[layer_i][draw_list_i], "DrawList");
19707
0
        TreePop();
19708
0
    }
19709
0
}
19710
19711
void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label)
19712
0
{
19713
0
    if (window == NULL)
19714
0
    {
19715
0
        BulletText("%s: NULL", label);
19716
0
        return;
19717
0
    }
19718
19719
0
    ImGuiContext& g = *GImGui;
19720
0
    const bool is_active = window->WasActive;
19721
0
    ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
19722
0
    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
19723
0
    const bool open = TreeNodeEx(label, tree_node_flags, "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*");
19724
0
    if (!is_active) { PopStyleColor(); }
19725
0
    if (IsItemHovered() && is_active)
19726
0
        GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
19727
0
    if (!open)
19728
0
        return;
19729
19730
0
    if (window->MemoryCompacted)
19731
0
        TextDisabled("Note: some memory buffers have been compacted/freed.");
19732
19733
0
    ImGuiWindowFlags flags = window->Flags;
19734
0
    DebugNodeDrawList(window, window->Viewport, window->DrawList, "DrawList");
19735
0
    BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f) Ideal (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y, window->ContentSizeIdeal.x, window->ContentSizeIdeal.y);
19736
0
    BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
19737
0
        (flags & ImGuiWindowFlags_ChildWindow)  ? "Child " : "",      (flags & ImGuiWindowFlags_Tooltip)     ? "Tooltip "   : "",  (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
19738
0
        (flags & ImGuiWindowFlags_Modal)        ? "Modal " : "",      (flags & ImGuiWindowFlags_ChildMenu)   ? "ChildMenu " : "",  (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
19739
0
        (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
19740
0
    BulletText("WindowClassId: 0x%08X", window->WindowClass.ClassId);
19741
0
    BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f) Scrollbar:%s%s", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y, window->ScrollbarX ? "X" : "", window->ScrollbarY ? "Y" : "");
19742
0
    BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
19743
0
    BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
19744
0
    for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
19745
0
    {
19746
0
        ImRect r = window->NavRectRel[layer];
19747
0
        if (r.Min.x >= r.Max.y && r.Min.y >= r.Max.y)
19748
0
            BulletText("NavLastIds[%d]: 0x%08X", layer, window->NavLastIds[layer]);
19749
0
        else
19750
0
            BulletText("NavLastIds[%d]: 0x%08X at +(%.1f,%.1f)(%.1f,%.1f)", layer, window->NavLastIds[layer], r.Min.x, r.Min.y, r.Max.x, r.Max.y);
19751
0
        DebugLocateItemOnHover(window->NavLastIds[layer]);
19752
0
    }
19753
0
    BulletText("NavLayersActiveMask: %X, NavLastChildNavWindow: %s", window->DC.NavLayersActiveMask, window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
19754
19755
0
    BulletText("Viewport: %d%s, ViewportId: 0x%08X, ViewportPos: (%.1f,%.1f)", window->Viewport ? window->Viewport->Idx : -1, window->ViewportOwned ? " (Owned)" : "", window->ViewportId, window->ViewportPos.x, window->ViewportPos.y);
19756
0
    BulletText("ViewportMonitor: %d", window->Viewport ? window->Viewport->PlatformMonitor : -1);
19757
0
    BulletText("DockId: 0x%04X, DockOrder: %d, Act: %d, Vis: %d", window->DockId, window->DockOrder, window->DockIsActive, window->DockTabIsVisible);
19758
0
    if (window->DockNode || window->DockNodeAsHost)
19759
0
        DebugNodeDockNode(window->DockNodeAsHost ? window->DockNodeAsHost : window->DockNode, window->DockNodeAsHost ? "DockNodeAsHost" : "DockNode");
19760
19761
0
    if (window->RootWindow != window)       { DebugNodeWindow(window->RootWindow, "RootWindow"); }
19762
0
    if (window->RootWindowDockTree != window->RootWindow) { DebugNodeWindow(window->RootWindowDockTree, "RootWindowDockTree"); }
19763
0
    if (window->ParentWindow != NULL)       { DebugNodeWindow(window->ParentWindow, "ParentWindow"); }
19764
0
    if (window->DC.ChildWindows.Size > 0)   { DebugNodeWindowsList(&window->DC.ChildWindows, "ChildWindows"); }
19765
0
    if (window->ColumnsStorage.Size > 0 && TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
19766
0
    {
19767
0
        for (int n = 0; n < window->ColumnsStorage.Size; n++)
19768
0
            DebugNodeColumns(&window->ColumnsStorage[n]);
19769
0
        TreePop();
19770
0
    }
19771
0
    DebugNodeStorage(&window->StateStorage, "Storage");
19772
0
    TreePop();
19773
0
}
19774
19775
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings* settings)
19776
0
{
19777
0
    Text("0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d",
19778
0
        settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed);
19779
0
}
19780
19781
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>* windows, const char* label)
19782
0
{
19783
0
    if (!TreeNode(label, "%s (%d)", label, windows->Size))
19784
0
        return;
19785
0
    for (int i = windows->Size - 1; i >= 0; i--) // Iterate front to back
19786
0
    {
19787
0
        PushID((*windows)[i]);
19788
0
        DebugNodeWindow((*windows)[i], "Window");
19789
0
        PopID();
19790
0
    }
19791
0
    TreePop();
19792
0
}
19793
19794
// FIXME-OPT: This is technically suboptimal, but it is simpler this way.
19795
void ImGui::DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int windows_size, ImGuiWindow* parent_in_begin_stack)
19796
0
{
19797
0
    for (int i = 0; i < windows_size; i++)
19798
0
    {
19799
0
        ImGuiWindow* window = windows[i];
19800
0
        if (window->ParentWindowInBeginStack != parent_in_begin_stack)
19801
0
            continue;
19802
0
        char buf[20];
19803
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "[%04d] Window", window->BeginOrderWithinContext);
19804
        //BulletText("[%04d] Window '%s'", window->BeginOrderWithinContext, window->Name);
19805
0
        DebugNodeWindow(window, buf);
19806
0
        Indent();
19807
0
        DebugNodeWindowsListByBeginStackParent(windows + i + 1, windows_size - i - 1, window);
19808
0
        Unindent();
19809
0
    }
19810
0
}
19811
19812
//-----------------------------------------------------------------------------
19813
// [SECTION] DEBUG LOG WINDOW
19814
//-----------------------------------------------------------------------------
19815
19816
void ImGui::DebugLog(const char* fmt, ...)
19817
0
{
19818
0
    va_list args;
19819
0
    va_start(args, fmt);
19820
0
    DebugLogV(fmt, args);
19821
0
    va_end(args);
19822
0
}
19823
19824
void ImGui::DebugLogV(const char* fmt, va_list args)
19825
0
{
19826
0
    ImGuiContext& g = *GImGui;
19827
0
    const int old_size = g.DebugLogBuf.size();
19828
0
    g.DebugLogBuf.appendf("[%05d] ", g.FrameCount);
19829
0
    g.DebugLogBuf.appendfv(fmt, args);
19830
0
    if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTTY)
19831
0
        IMGUI_DEBUG_PRINTF("%s", g.DebugLogBuf.begin() + old_size);
19832
0
    g.DebugLogIndex.append(g.DebugLogBuf.c_str(), old_size, g.DebugLogBuf.size());
19833
0
}
19834
19835
void ImGui::ShowDebugLogWindow(bool* p_open)
19836
0
{
19837
0
    ImGuiContext& g = *GImGui;
19838
0
    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
19839
0
        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 12.0f), ImGuiCond_FirstUseEver);
19840
0
    if (!Begin("Dear ImGui Debug Log", p_open) || GetCurrentWindow()->BeginCount > 1)
19841
0
    {
19842
0
        End();
19843
0
        return;
19844
0
    }
19845
19846
0
    AlignTextToFramePadding();
19847
0
    Text("Log events:");
19848
0
    SameLine(); CheckboxFlags("All", &g.DebugLogFlags, ImGuiDebugLogFlags_EventMask_);
19849
0
    SameLine(); CheckboxFlags("ActiveId", &g.DebugLogFlags, ImGuiDebugLogFlags_EventActiveId);
19850
0
    SameLine(); CheckboxFlags("Focus", &g.DebugLogFlags, ImGuiDebugLogFlags_EventFocus);
19851
0
    SameLine(); CheckboxFlags("Popup", &g.DebugLogFlags, ImGuiDebugLogFlags_EventPopup);
19852
0
    SameLine(); CheckboxFlags("Nav", &g.DebugLogFlags, ImGuiDebugLogFlags_EventNav);
19853
0
    SameLine(); CheckboxFlags("Clipper", &g.DebugLogFlags, ImGuiDebugLogFlags_EventClipper);
19854
0
    SameLine(); CheckboxFlags("IO", &g.DebugLogFlags, ImGuiDebugLogFlags_EventIO);
19855
0
    SameLine(); CheckboxFlags("Docking", &g.DebugLogFlags, ImGuiDebugLogFlags_EventDocking);
19856
0
    SameLine(); CheckboxFlags("Viewport", &g.DebugLogFlags, ImGuiDebugLogFlags_EventViewport);
19857
19858
0
    if (SmallButton("Clear"))
19859
0
    {
19860
0
        g.DebugLogBuf.clear();
19861
0
        g.DebugLogIndex.clear();
19862
0
    }
19863
0
    SameLine();
19864
0
    if (SmallButton("Copy"))
19865
0
        SetClipboardText(g.DebugLogBuf.c_str());
19866
0
    BeginChild("##log", ImVec2(0.0f, 0.0f), true, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar);
19867
19868
0
    ImGuiListClipper clipper;
19869
0
    clipper.Begin(g.DebugLogIndex.size());
19870
0
    while (clipper.Step())
19871
0
        for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++)
19872
0
        {
19873
0
            const char* line_begin = g.DebugLogIndex.get_line_begin(g.DebugLogBuf.c_str(), line_no);
19874
0
            const char* line_end = g.DebugLogIndex.get_line_end(g.DebugLogBuf.c_str(), line_no);
19875
0
            TextUnformatted(line_begin, line_end);
19876
0
            ImRect text_rect = g.LastItemData.Rect;
19877
0
            if (IsItemHovered())
19878
0
                for (const char* p = line_begin; p < line_end - 10; p++)
19879
0
                {
19880
0
                    ImGuiID id = 0;
19881
0
                    if (p[0] != '0' || (p[1] != 'x' && p[1] != 'X') || sscanf(p + 2, "%X", &id) != 1)
19882
0
                        continue;
19883
0
                    ImVec2 p0 = CalcTextSize(line_begin, p);
19884
0
                    ImVec2 p1 = CalcTextSize(p, p + 10);
19885
0
                    g.LastItemData.Rect = ImRect(text_rect.Min + ImVec2(p0.x, 0.0f), text_rect.Min + ImVec2(p0.x + p1.x, p1.y));
19886
0
                    if (IsMouseHoveringRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, true))
19887
0
                        DebugLocateItemOnHover(id);
19888
0
                    p += 10;
19889
0
                }
19890
0
        }
19891
0
    if (GetScrollY() >= GetScrollMaxY())
19892
0
        SetScrollHereY(1.0f);
19893
0
    EndChild();
19894
19895
0
    End();
19896
0
}
19897
19898
//-----------------------------------------------------------------------------
19899
// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, STACK TOOL)
19900
//-----------------------------------------------------------------------------
19901
19902
static const ImU32 DEBUG_LOCATE_ITEM_COLOR = IM_COL32(0, 255, 0, 255);  // Green
19903
19904
void ImGui::DebugLocateItem(ImGuiID target_id)
19905
0
{
19906
0
    ImGuiContext& g = *GImGui;
19907
0
    g.DebugLocateId = target_id;
19908
0
    g.DebugLocateFrames = 2;
19909
0
}
19910
19911
void ImGui::DebugLocateItemOnHover(ImGuiID target_id)
19912
0
{
19913
0
    if (target_id == 0 || !IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenBlockedByPopup))
19914
0
        return;
19915
0
    ImGuiContext& g = *GImGui;
19916
0
    DebugLocateItem(target_id);
19917
0
    GetForegroundDrawList(g.CurrentWindow)->AddRect(g.LastItemData.Rect.Min - ImVec2(3.0f, 3.0f), g.LastItemData.Rect.Max + ImVec2(3.0f, 3.0f), DEBUG_LOCATE_ITEM_COLOR);
19918
0
}
19919
19920
void ImGui::DebugLocateItemResolveWithLastItem()
19921
0
{
19922
0
    ImGuiContext& g = *GImGui;
19923
0
    ImGuiLastItemData item_data = g.LastItemData;
19924
0
    g.DebugLocateId = 0;
19925
0
    ImDrawList* draw_list = GetForegroundDrawList(g.CurrentWindow);
19926
0
    ImRect r = item_data.Rect;
19927
0
    r.Expand(3.0f);
19928
0
    ImVec2 p1 = g.IO.MousePos;
19929
0
    ImVec2 p2 = ImVec2((p1.x < r.Min.x) ? r.Min.x : (p1.x > r.Max.x) ? r.Max.x : p1.x, (p1.y < r.Min.y) ? r.Min.y : (p1.y > r.Max.y) ? r.Max.y : p1.y);
19930
0
    draw_list->AddRect(r.Min, r.Max, DEBUG_LOCATE_ITEM_COLOR);
19931
0
    draw_list->AddLine(p1, p2, DEBUG_LOCATE_ITEM_COLOR);
19932
0
}
19933
19934
// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
19935
void ImGui::UpdateDebugToolItemPicker()
19936
3.00k
{
19937
3.00k
    ImGuiContext& g = *GImGui;
19938
3.00k
    g.DebugItemPickerBreakId = 0;
19939
3.00k
    if (!g.DebugItemPickerActive)
19940
3.00k
        return;
19941
19942
0
    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
19943
0
    SetMouseCursor(ImGuiMouseCursor_Hand);
19944
0
    if (IsKeyPressed(ImGuiKey_Escape))
19945
0
        g.DebugItemPickerActive = false;
19946
0
    const bool change_mapping = g.IO.KeyMods == (ImGuiMod_Ctrl | ImGuiMod_Shift);
19947
0
    if (!change_mapping && IsMouseClicked(g.DebugItemPickerMouseButton) && hovered_id)
19948
0
    {
19949
0
        g.DebugItemPickerBreakId = hovered_id;
19950
0
        g.DebugItemPickerActive = false;
19951
0
    }
19952
0
    for (int mouse_button = 0; mouse_button < 3; mouse_button++)
19953
0
        if (change_mapping && IsMouseClicked(mouse_button))
19954
0
            g.DebugItemPickerMouseButton = (ImU8)mouse_button;
19955
0
    SetNextWindowBgAlpha(0.70f);
19956
0
    BeginTooltip();
19957
0
    Text("HoveredId: 0x%08X", hovered_id);
19958
0
    Text("Press ESC to abort picking.");
19959
0
    const char* mouse_button_names[] = { "Left", "Right", "Middle" };
19960
0
    if (change_mapping)
19961
0
        Text("Remap w/ Ctrl+Shift: click anywhere to select new mouse button.");
19962
0
    else
19963
0
        TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click %s Button to break in debugger! (remap w/ Ctrl+Shift)", mouse_button_names[g.DebugItemPickerMouseButton]);
19964
0
    EndTooltip();
19965
0
}
19966
19967
// [DEBUG] Stack Tool: update queries. Called by NewFrame()
19968
void ImGui::UpdateDebugToolStackQueries()
19969
3.00k
{
19970
3.00k
    ImGuiContext& g = *GImGui;
19971
3.00k
    ImGuiStackTool* tool = &g.DebugStackTool;
19972
19973
    // Clear hook when stack tool is not visible
19974
3.00k
    g.DebugHookIdInfo = 0;
19975
3.00k
    if (g.FrameCount != tool->LastActiveFrame + 1)
19976
3.00k
        return;
19977
19978
    // Update queries. The steps are: -1: query Stack, >= 0: query each stack item
19979
    // We can only perform 1 ID Info query every frame. This is designed so the GetID() tests are cheap and constant-time
19980
1
    const ImGuiID query_id = g.HoveredIdPreviousFrame ? g.HoveredIdPreviousFrame : g.ActiveId;
19981
1
    if (tool->QueryId != query_id)
19982
0
    {
19983
0
        tool->QueryId = query_id;
19984
0
        tool->StackLevel = -1;
19985
0
        tool->Results.resize(0);
19986
0
    }
19987
1
    if (query_id == 0)
19988
1
        return;
19989
19990
    // Advance to next stack level when we got our result, or after 2 frames (in case we never get a result)
19991
0
    int stack_level = tool->StackLevel;
19992
0
    if (stack_level >= 0 && stack_level < tool->Results.Size)
19993
0
        if (tool->Results[stack_level].QuerySuccess || tool->Results[stack_level].QueryFrameCount > 2)
19994
0
            tool->StackLevel++;
19995
19996
    // Update hook
19997
0
    stack_level = tool->StackLevel;
19998
0
    if (stack_level == -1)
19999
0
        g.DebugHookIdInfo = query_id;
20000
0
    if (stack_level >= 0 && stack_level < tool->Results.Size)
20001
0
    {
20002
0
        g.DebugHookIdInfo = tool->Results[stack_level].ID;
20003
0
        tool->Results[stack_level].QueryFrameCount++;
20004
0
    }
20005
0
}
20006
20007
// [DEBUG] Stack tool: hooks called by GetID() family functions
20008
void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end)
20009
0
{
20010
0
    ImGuiContext& g = *GImGui;
20011
0
    ImGuiWindow* window = g.CurrentWindow;
20012
0
    ImGuiStackTool* tool = &g.DebugStackTool;
20013
20014
    // Step 0: stack query
20015
    // This assumes that the ID was computed with the current ID stack, which tends to be the case for our widget.
20016
0
    if (tool->StackLevel == -1)
20017
0
    {
20018
0
        tool->StackLevel++;
20019
0
        tool->Results.resize(window->IDStack.Size + 1, ImGuiStackLevelInfo());
20020
0
        for (int n = 0; n < window->IDStack.Size + 1; n++)
20021
0
            tool->Results[n].ID = (n < window->IDStack.Size) ? window->IDStack[n] : id;
20022
0
        return;
20023
0
    }
20024
20025
    // Step 1+: query for individual level
20026
0
    IM_ASSERT(tool->StackLevel >= 0);
20027
0
    if (tool->StackLevel != window->IDStack.Size)
20028
0
        return;
20029
0
    ImGuiStackLevelInfo* info = &tool->Results[tool->StackLevel];
20030
0
    IM_ASSERT(info->ID == id && info->QueryFrameCount > 0);
20031
20032
0
    switch (data_type)
20033
0
    {
20034
0
    case ImGuiDataType_S32:
20035
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%d", (int)(intptr_t)data_id);
20036
0
        break;
20037
0
    case ImGuiDataType_String:
20038
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%.*s", data_id_end ? (int)((const char*)data_id_end - (const char*)data_id) : (int)strlen((const char*)data_id), (const char*)data_id);
20039
0
        break;
20040
0
    case ImGuiDataType_Pointer:
20041
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "(void*)0x%p", data_id);
20042
0
        break;
20043
0
    case ImGuiDataType_ID:
20044
0
        if (info->Desc[0] != 0) // PushOverrideID() is often used to avoid hashing twice, which would lead to 2 calls to DebugHookIdInfo(). We prioritize the first one.
20045
0
            return;
20046
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "0x%08X [override]", id);
20047
0
        break;
20048
0
    default:
20049
0
        IM_ASSERT(0);
20050
0
    }
20051
0
    info->QuerySuccess = true;
20052
0
    info->DataType = data_type;
20053
0
}
20054
20055
static int StackToolFormatLevelInfo(ImGuiStackTool* tool, int n, bool format_for_ui, char* buf, size_t buf_size)
20056
0
{
20057
0
    ImGuiStackLevelInfo* info = &tool->Results[n];
20058
0
    ImGuiWindow* window = (info->Desc[0] == 0 && n == 0) ? ImGui::FindWindowByID(info->ID) : NULL;
20059
0
    if (window)                                                                 // Source: window name (because the root ID don't call GetID() and so doesn't get hooked)
20060
0
        return ImFormatString(buf, buf_size, format_for_ui ? "\"%s\" [window]" : "%s", window->Name);
20061
0
    if (info->QuerySuccess)                                                     // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id)
20062
0
        return ImFormatString(buf, buf_size, (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", info->Desc);
20063
0
    if (tool->StackLevel < tool->Results.Size)                                  // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers.
20064
0
        return (*buf = 0);
20065
#ifdef IMGUI_ENABLE_TEST_ENGINE
20066
    if (const char* label = ImGuiTestEngine_FindItemDebugLabel(GImGui, info->ID))   // Source: ImGuiTestEngine's ItemInfo()
20067
        return ImFormatString(buf, buf_size, format_for_ui ? "??? \"%s\"" : "%s", label);
20068
#endif
20069
0
    return ImFormatString(buf, buf_size, "???");
20070
0
}
20071
20072
// Stack Tool: Display UI
20073
void ImGui::ShowStackToolWindow(bool* p_open)
20074
0
{
20075
0
    ImGuiContext& g = *GImGui;
20076
0
    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
20077
0
        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 8.0f), ImGuiCond_FirstUseEver);
20078
0
    if (!Begin("Dear ImGui Stack Tool", p_open) || GetCurrentWindow()->BeginCount > 1)
20079
0
    {
20080
0
        End();
20081
0
        return;
20082
0
    }
20083
20084
    // Display hovered/active status
20085
0
    ImGuiStackTool* tool = &g.DebugStackTool;
20086
0
    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
20087
0
    const ImGuiID active_id = g.ActiveId;
20088
#ifdef IMGUI_ENABLE_TEST_ENGINE
20089
    Text("HoveredId: 0x%08X (\"%s\"), ActiveId:  0x%08X (\"%s\")", hovered_id, hovered_id ? ImGuiTestEngine_FindItemDebugLabel(&g, hovered_id) : "", active_id, active_id ? ImGuiTestEngine_FindItemDebugLabel(&g, active_id) : "");
20090
#else
20091
0
    Text("HoveredId: 0x%08X, ActiveId:  0x%08X", hovered_id, active_id);
20092
0
#endif
20093
0
    SameLine();
20094
0
    MetricsHelpMarker("Hover an item with the mouse to display elements of the ID Stack leading to the item's final ID.\nEach level of the stack correspond to a PushID() call.\nAll levels of the stack are hashed together to make the final ID of a widget (ID displayed at the bottom level of the stack).\nRead FAQ entry about the ID stack for details.");
20095
20096
    // CTRL+C to copy path
20097
0
    const float time_since_copy = (float)g.Time - tool->CopyToClipboardLastTime;
20098
0
    Checkbox("Ctrl+C: copy path to clipboard", &tool->CopyToClipboardOnCtrlC);
20099
0
    SameLine();
20100
0
    TextColored((time_since_copy >= 0.0f && time_since_copy < 0.75f && ImFmod(time_since_copy, 0.25f) < 0.25f * 0.5f) ? ImVec4(1.f, 1.f, 0.3f, 1.f) : ImVec4(), "*COPIED*");
20101
0
    if (tool->CopyToClipboardOnCtrlC && IsKeyDown(ImGuiMod_Ctrl) && IsKeyPressed(ImGuiKey_C))
20102
0
    {
20103
0
        tool->CopyToClipboardLastTime = (float)g.Time;
20104
0
        char* p = g.TempBuffer.Data;
20105
0
        char* p_end = p + g.TempBuffer.Size;
20106
0
        for (int stack_n = 0; stack_n < tool->Results.Size && p + 3 < p_end; stack_n++)
20107
0
        {
20108
0
            *p++ = '/';
20109
0
            char level_desc[256];
20110
0
            StackToolFormatLevelInfo(tool, stack_n, false, level_desc, IM_ARRAYSIZE(level_desc));
20111
0
            for (int n = 0; level_desc[n] && p + 2 < p_end; n++)
20112
0
            {
20113
0
                if (level_desc[n] == '/')
20114
0
                    *p++ = '\\';
20115
0
                *p++ = level_desc[n];
20116
0
            }
20117
0
        }
20118
0
        *p = '\0';
20119
0
        SetClipboardText(g.TempBuffer.Data);
20120
0
    }
20121
20122
    // Display decorated stack
20123
0
    tool->LastActiveFrame = g.FrameCount;
20124
0
    if (tool->Results.Size > 0 && BeginTable("##table", 3, ImGuiTableFlags_Borders))
20125
0
    {
20126
0
        const float id_width = CalcTextSize("0xDDDDDDDD").x;
20127
0
        TableSetupColumn("Seed", ImGuiTableColumnFlags_WidthFixed, id_width);
20128
0
        TableSetupColumn("PushID", ImGuiTableColumnFlags_WidthStretch);
20129
0
        TableSetupColumn("Result", ImGuiTableColumnFlags_WidthFixed, id_width);
20130
0
        TableHeadersRow();
20131
0
        for (int n = 0; n < tool->Results.Size; n++)
20132
0
        {
20133
0
            ImGuiStackLevelInfo* info = &tool->Results[n];
20134
0
            TableNextColumn();
20135
0
            Text("0x%08X", (n > 0) ? tool->Results[n - 1].ID : 0);
20136
0
            TableNextColumn();
20137
0
            StackToolFormatLevelInfo(tool, n, true, g.TempBuffer.Data, g.TempBuffer.Size);
20138
0
            TextUnformatted(g.TempBuffer.Data);
20139
0
            TableNextColumn();
20140
0
            Text("0x%08X", info->ID);
20141
0
            if (n == tool->Results.Size - 1)
20142
0
                TableSetBgColor(ImGuiTableBgTarget_CellBg, GetColorU32(ImGuiCol_Header));
20143
0
        }
20144
0
        EndTable();
20145
0
    }
20146
0
    End();
20147
0
}
20148
20149
#else
20150
20151
void ImGui::ShowMetricsWindow(bool*) {}
20152
void ImGui::ShowFontAtlas(ImFontAtlas*) {}
20153
void ImGui::DebugNodeColumns(ImGuiOldColumns*) {}
20154
void ImGui::DebugNodeDrawList(ImGuiWindow*, ImGuiViewportP*, const ImDrawList*, const char*) {}
20155
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList*, const ImDrawList*, const ImDrawCmd*, bool, bool) {}
20156
void ImGui::DebugNodeFont(ImFont*) {}
20157
void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {}
20158
void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {}
20159
void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {}
20160
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {}
20161
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>*, const char*) {}
20162
void ImGui::DebugNodeViewport(ImGuiViewportP*) {}
20163
20164
void ImGui::DebugLog(const char*, ...) {}
20165
void ImGui::DebugLogV(const char*, va_list) {}
20166
void ImGui::ShowDebugLogWindow(bool*) {}
20167
void ImGui::ShowStackToolWindow(bool*) {}
20168
void ImGui::DebugHookIdInfo(ImGuiID, ImGuiDataType, const void*, const void*) {}
20169
void ImGui::UpdateDebugToolItemPicker() {}
20170
void ImGui::UpdateDebugToolStackQueries() {}
20171
20172
#endif // #ifndef IMGUI_DISABLE_DEBUG_TOOLS
20173
20174
//-----------------------------------------------------------------------------
20175
20176
// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
20177
// Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github.
20178
#ifdef IMGUI_INCLUDE_IMGUI_USER_INL
20179
#include "imgui_user.inl"
20180
#endif
20181
20182
//-----------------------------------------------------------------------------
20183
20184
#endif // #ifndef IMGUI_DISABLE